351
VSim In Depth Release 8.2.1 Tech-X Corporation Jan 30, 2018

VSim In Depth

Embed Size (px)

Citation preview

Page 1: VSim In Depth

VSim In DepthRelease 8.2.1

Tech-X Corporation

Jan 30, 2018

Page 2: VSim In Depth

2

Page 3: VSim In Depth

CONTENTS

1 VSim In Depth Introduction 1

2 Basic Concepts 3

3 VSimComposer Visual Setup Reference 15

4 Text-based Input File Overview 51

5 Tutorials 63

6 Cylindrical Coordinates 99

7 Geometries 103

8 Macros 105

9 Analysis Window 247

10 Advanced Concepts 287

11 Troubleshooting and FAQ 339

12 References 345

Bibliography 347

i

Page 4: VSim In Depth

ii

Page 5: VSim In Depth

CHAPTER

ONE

VSIM IN DEPTH INTRODUCTION

1.1 VSim In Depth Introduction

Welcome to VSim, the relativistic, arbitrary dimensional, hybrid plasma and beam simulation code. VSim consists oftwo major components:

• Vorpal - the VSim computational engine (“vorpal” for parallel, “vorpalser” for serial)

• VSimComposer - the graphical user interface

VSimComposer provides an interface that allows you to edit and validate your simulation input files, run VSim simu-lations, and visualize results using the VisIt-based Visualization pane embedded within VSimComposer. You can alsoedit VSim input files in the text editor of your choice, perform calculations with the easy-to-run, command-line-drivenVorpal engine, and then run the visualization tool of your choice.

In this manual, VSim In Depth, we go beyond VSimComposer, and elaborate on the basic concepts of VSim simu-lations by examining VSim input files (files with the .pre extension). This manual will demonstrate how to take anexisting VSim input file and modify more than just the key parameters in order to create your own custom simulations.This manual assumes that the reader is familiar with the VSim Quick Start manual.

Within this manual there are several tutorials on how to modify input files as well as detailed descriptions of all themacros available when writing an input file. In addition there are guides on how to run the VSim computational engine,Vorpal, outside of the VSimComposer interface (e.g. on a super computer) as well as guides on how to use the postprocessing analysis features of VSimComposer.

1

Page 6: VSim In Depth

VSim In Depth, Release 8.2.1

2 Chapter 1. VSim In Depth Introduction

Page 7: VSim In Depth

CHAPTER

TWO

BASIC CONCEPTS

2.1 Units

All physical attributes in Vorpal are expressed in SI units unless otherwise mentioned.

2.2 Default Values

2.2.1 Reporting or Verbosity levels

By default, VSim tries to give meaningful set of detailed output that gives information on what the physics engine isdoing. By default, the Vorpal engine operates at the information level while many examples run at the Notice level.The complete list of reporting levels are:

Emergency Only give messages on things that stop the code

Alert Only give messages on things that stop the code or possibly stop the code

Critical Provide just the critical message

Error Give messages that might be errors

Warning Give messages that might be a problem (code may or may not really know)

Notice Give notices on progress

Information Give move verbose information on progress

Debug level 1 Give information useful for debugging

Debug level 2 Give more information useful for debugging

Debug level 3 Give very verbose information for debugging

For text-based input, the Verbosity Macro File is useful for setting the various levels.

2.2.2 Field Boundary Conditions

Electromagnetic simulations

The default boundary conditions for an electromagnetic simulation are perfect conductors.

3

Page 8: VSim In Depth

VSim In Depth, Release 8.2.1

Note: Tech-X strongly encourages that you explicitly specify any boundary conditions in your simulation and notrely on the defaults

Electrostatic simulations

There are no default boundary conditions for an electrostatic simulation.

If using the MultiField framework, please see Solverbcs Macro File for more details on types of electrostatic boundaryconditions you can use.

If using the EmField, kind=yeeStaticEmField framework, please see yeestaticemfield_bc for more details on types ofelectrostatic boundary conditions you can use.

2.2.3 Particle Boundary Conditions

There are no default boundary conditions for particles in a simulation.

If the simulation has particles, and the particles escape the domain of simulation, Vorpal will crash.

Please see particlesink for more details on types of particle boundary conditions you can use.

2.3 The Simulation Grid

This section is more advanced than vsim-quick-start, which this section assumes the user has reviewed.

Every object in a simulation interacts with a 3D grid, in either Cartesian or cylindrical coordinates. Fields are rep-resented on the grid, and positions relative to the grid determine which particles interact through collisions and howfields are interpolated to the particles.

2.3.1 Cells and Dimensions

This section discusses basic concepts involved in setting up a simulation grid. Understanding simulation grid setup is aprerequisite to defining a grid in an input file. For the purposes of this guide, all examples are represented in Cartesiancoordinates.

The grid consists of:

• cells

• set of dimensions, or lengths, along the x, y, and z axes

The number of cells in the grid determines the resolution of the simulation.

This document’s illustrations are based on a right-handed coordinate system. In this coordinate system, the axes arelaid out as follows:

• X = left to right

• Y = front to back

• Z = bottom to top

The example simulations in this document refer to lower and upper ends of the simulation, where the X, Y, Z, coordi-nate mapping references in explanations are:

4 Chapter 2. Basic Concepts

Page 9: VSim In Depth

VSim In Depth, Release 8.2.1

• Left: X-lower

• Right: X-upper

• Front: Y-lower

• Back: Y-upper

• Bottom: Z-lower

• Top: Z-upper

All units are expressed in SI (meters, kilograms, and seconds).

Note: Higher dimension information is ignored when it is provided for a lower dimension simulations(that is, when 3D information is provided for 1D or 2D, or when 2D information is provided for 1D).

You can specify the location of the grid’s start point: the lower left, front corner of the grid (that is, the position atwhich x = 0 cells, y = 0 cells, and z = 0 cells). If you do not specify the start point’s location, the start point a locationis assigned to x = 0 m, y = 0 m, and z = 0 m.

Note: Tech-X recommends that you start with a low-resolution simulation and make sure that it runs tocompletion without any problems. Then increase the resolution as needed.

Let’s examine a 3D Cartesian grid for a simple electromagnetic simulation in which:

• The grid has 40 cells along the x axis, 40 cells along the y axis, and 20 cells along the z axis.

• The lengths of the grid are X = 1.e-4 m, Y = 1.e-4 m, and Z = 5.e-5 m.

• The start point is located at X = 0 m, Y = -5.e-5 m, and Z = -2.5e-5 m.

• The dimensions of each cell are 2.5e-6 m along the x, y, and z axes.

The figure of the 3D Cartesian grid shows cells and dimensions for this example. The lower bounds of the grid areat x = 0 cells, y = 0 cells, and z = 0 cells. The upper bounds are at x = 40 cells, y = 40 cells, and z = 20 cells. Theuser-defined cells are in red. The user-defined dimensions are in blue. The gray cuboid encloses the cells in the grid.

Vorpal uses guard cells, which are cells located outside the user-defined simulation grid, for parallel processing andother computational purposes. You can also use guard cells when you describe boundary conditions. The number ofguard cells that Vorpal extends the user-defined 3D Cartesian grid by, will depend on the type of field in question. Fora field where charge is deposited, such as SumRhoJ or a user defined “depField”, the grid is extended by:

• One guard cell at the lower end of the x axis and two guard cells at the upper end

• One guard cell at the lower end of the y axis and two guard cells at the upper end

• One guard cell at the lower end of the z axis and two guard cells at the upper end

For a non-dep field, where charge is not deposited, such as the electric or magnetic field, the grid is extended by:

• One guard cell at the lower end of the x axis and one guard cell at the upper end

• One guard cell at the lower end of the y axis and one guard cell at the upper end

• One guard cell at the lower end of the z axis and one guard cell at the upper end

The overlap parameter determines the number of cells that must be shared between MPI ranks, so for each parallelprocess it is the number of cells it needs to be aware of beyond the edge of its domain. If you have electrostatic particlesthat travel more than once cell per timestep, or particles with large stencils, then manual setting of overlap maybe necessary. You can modify the number of guard cells used in your simulation with the maxIntDepHalfWidth

2.3. The Simulation Grid 5

Page 10: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 2.1: Cartesian grid showing cells and dimensions

parameter found in the Grid block, or overriding the value outright with the overlap parameter found in the Fieldblock of MultiField simulations. Please see the vsim-reference for more information.

Note: The user-defined grid is called the physical domain. The grid extended by Vorpal is called theextended domain.

For a non-dep field such as the electric or magnetic field, the user-defined Cartesian grid with 40 cells along the x axis,40 cells along the y axis, and 20 cells along the z axis is extended by Vorpal to 42 cells along the x axis, 42 cells alongthe y axis, and 22 cells along the z axis. The lower bounds of the grid extended by Vorpal are at x = -1 cells, y = -1cells, and z = -1 cells. The upper bounds are at x = 41 cells, y = 41 cells, and z = 21 cells.

The figure of the Cartesian grid extended by Vorpal shows how Vorpal adds additional guard cells to extend the user-defined grid. The user-defined cells are in red. The user-defined dimensions are in blue. The guard cells that Vorpaladds to extend the grid are in green. The total volume now encloses both the user-defined cells and the guard cellsadded by Vorpal.

Electric and Magnetic Fields

On a Yee mesh, electric fields are located on the edges of grid cells, and magnetic fields are located on the faces of thecell surfaces as shown in the figure.

Electromagnetic and Electrostatic Boundaries

To describe an electromagnetic or electrostatic boundary, we specify the lower bounds and upper bounds of the cells.Let’s examine this concept on a 2D user-defined grid with 10 cells along the x axis and 5 cells along the y axis. Thefigure in this section shows these cells. In the figure, the user-defined grid cells are in red. The guard cells added byVorpal are in green.

In the figure, the top panel illustrates the electric fields boundaries. The arrows represent the field lines and the electricfield components are labeled by indices. Note that on the bottom row the electric field is set on the cells inside the

6 Chapter 2. Basic Concepts

Page 11: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 2.2: Cartesian grid extended by Vorpal

Fig. 2.3: Electric and magnetic fields on a grid cell

2.3. The Simulation Grid 7

Page 12: VSim In Depth

VSim In Depth, Release 8.2.1

boundary because they own the bottom edges that form the boundary.

We want to define the bounds for electric charges in a row of cells at the bottom of the grid. The lower bounds are at0,0. The upper bounds are at 10,1.

We also want to define the bounds for electric charges in a row of cells at the top of the grid. The lower bounds are at0,5. The upper bounds are at 10,6.

The bottom panel of the figure shows the lower bounds and upper bounds for electric charges, highlighting the cellsenclosed in the bounds for the electric charges in both rows of cells. Again these are not simply the guard cells becauseyou need the cells containing the bottom edges of interest.

Fig. 2.4: 2D extended grid showing lower bounds and upper bounds for electric charges

For more information about the simulation grid, see the vsim-reference.

8 Chapter 2. Basic Concepts

Page 13: VSim In Depth

VSim In Depth, Release 8.2.1

Electromagnetic Boundaries and Particle Sinks

It is important to note that upper and lowerBounds defined in VSim are inclusive of the specified lower bound, andexclusive of the upper bound. If the boundary condition is specify in on an edge or face, the bounds are applied tothe relevant edge/face, whereas if the boundary condition (or particle sink) is specified on a cell center the bounds areapplied at the relevant cell center. If attempting to set a particle sink and edge/face field boundary condition at thesame place on the lower side of the simulation, the bounds specified must be different. This is shown in the figurebelow

Fig. 2.5: Bounds necessary for an upper/lowerX particle sink and conducting boundary condition.

In the figure above the green dots mark cells that will have a particle sink applied to them, and the red arrows the celledges that will have a conducting boundary condition applied, given the bounds specified.

Now that we have examined the simulation grid, we are ready to examine the syntax used to define a simulation modelon the grid in Input File Elements. We begin with an overview of an input file.

2.4 Key Parameters

Starting in VSim 6.2 is the ability to create key parameters. These variables are visible in the Editor pane of the Setuptab in VSimComposer, and they can be modified without the user having to sift through the input file. They are useful

2.4. Key Parameters 9

Page 14: VSim In Depth

VSim In Depth, Release 8.2.1

when creating a base simulation that can be easily modified to simulate different phenomena within the same basesimulation. This tutorial is for power users who wish to use key parameters within their own simulations and who arefamiliar with the vsimcomposer-intro. As preparation for a discussion of key parameters, the user must be comfortablewith accessing the input file, as discussed in Input File Elements.

The two main components of the key parameters feature are the XSim block and the XVar block. An example XSimand XVar blocks in a simulation input file are highlighted in the below figure.

Fig. 2.6: Example XSim and XVar blocks in a simulationinput file

A description of the elements of these blocks and their effect on the Parameters view in the VSimComposer Setup tabis given in the following sections.

2.4.1 XSim Block

Given below is a template XSim block that can be modified to fit any file:

<XSim simulationName>shortDescription = "Simulation Name"description = "Description of the simulation."longDescription = "Longer description of the simulation."image = "simulationName.png"thumbnail = "simulationNameTn.png"

</XSim>

Each line in this block is explained below:

1. image - The image parameter should give the name of a picture, located in the same directory as the input file,that will be given on the right hand side of the Editor pane in the Setup tab. Frequently, this image is used toillustrate key parameters such as dimensions of a physical structure. 400 by 500 pixels is a good image size.

10 Chapter 2. Basic Concepts

Page 15: VSim In Depth

VSim In Depth, Release 8.2.1

2. longDescription - This text block will be visible above the image, and is generally used to give a description ofwhat the simulation does, and what will happen when key parameters are modified.

Fig. 2.7: The image and longDescription in the Parameters View.

The three following parameters are only useful to very advanced users who are creating, and placing inputfiles in the Examples directory of VSimComposer. The examples directory can be found in [VorpalInstallDirec-tory]ContentsExamples.

3. thumbnail - This is the small image that is visible when you select an example file, located in the same directoryas the input file. 250 x 250 pixels in a good image size.

4. shortDescription - This is the name that will be given to the example file.

5. description - This is the description given in the window on the right side in the examples window.

6. analyzers[SCRIPT] - This will cause VSimComposer to load the analysis script specified by SCRIPT, locatedin the same directory as the input file, for use in the Analyze Window.

2.4.2 XVar Block

Key parameters can be created in the input file of a simulation, and appear in the Setup tab in VSimComposer as seenbelow boxed in red.

To create these parameters, the user must modify the input file and add XVar blocks, in the same way that the user mustadd an XSim block as described in the preceding section. It is the practice of Tech-X developers to first declare theprimary variables with a default value, then give the XVar blocks for the primary variables below that. Given below isa template XVar block that can be modified to fit any file:

$ variableName = default value<XVar variableName>

description = "Description of the variable"

2.4. Key Parameters 11

Page 16: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 2.8: Select An Example Window

Fig. 2.9: Key parameters

12 Chapter 2. Basic Concepts

Page 17: VSim In Depth

VSim In Depth, Release 8.2.1

min = minimum valuemax = maximum value

</XVar>

Each line in this block is explained below:

1. variableName - The very first line, above the XVar block, sets the default value of the variable.

2. <XVar variableName> - This line, which begins the XVar block, must exactly match the name of the variablegiven in the line preceding it.

2. description - This text should describe the variable and will appear when the cursor is placed over the variablename.

3. min - This is the minimum value for the variable and is optional. This can be very useful with certain simulationparameters such as cell size that can cause an instability if incorrectly specified.

4. max - This is the maximum value for the variable and is optional.

Note: The name of the key parameter will turn red if there is no value given for the parameter, or if the value is notgreater than or equal to min and less than or equal to max, if they are specified.

2.5 Output Files

All data produced by VSim is in SI units and output using the HDF5 data file format. These output files are dumpedas defined by the user; they can be written at the end of a simulation, for example, or every n steps to create a timeseries that can be used to see how a system evolves over time. Additionally, these output files can be used to restart arun and continue from a given point; for example, if a user has run a simulation for 1000 time steps and wishes to seehow the simulation progresses if run for another 1000.

Execution of the computational engine leads to the generation of the data from the simulation in the form of HDF5.h5 files. There are separate executables for serial and parallel runs. For a more detailed description of the output fileformat, see HDF5 Format Vorpal Output Files.

2.5. Output Files 13

Page 18: VSim In Depth

VSim In Depth, Release 8.2.1

14 Chapter 2. Basic Concepts

Page 19: VSim In Depth

CHAPTER

THREE

VSIMCOMPOSER VISUAL SETUP REFERENCE

3.1 VSimComposer Visual Setup

In the following sections, definitions for the property/value pairs for VSimComposer’s visual setup can be found.

Contents

• Description Properties

• Constants Properties

• Parameters Properties

• Basic Settings Properties

• Functions Properties

• SpaceTimeFunctions Properties

• Materials Properties

– Customizing Materials

• Geometries Properties

– CSG

– Boolean Operations

– Imported

• Grids Properties

• Field Dynamics Properties

– Fields Properties

* Initial Condition

– FieldBoundaryConditions Properties

– CurrentDistributions Properties

– PoissonSolver Properties

• Particle Dynamics Properties

– KineticParticles

* Charged Particles

15

Page 20: VSim In Depth

VSim In Depth, Release 8.2.1

* Electrons

· Secondary Electron Emitter

* Neutral Particles

· Sputter Emitter

– Particle Loader Properties

– Settable Flux Emitter Properties

– TestParticleSpecies Properties

* Field Scaling Electrons

· Field Scaling Electron Loader

– ParticleBoundaryCondition Properties

– BackgroundGases Properties

– Collisions Properties

* Electron Neutral Fluid Collisions

· Elastic

· Excitation

· Ionization

* Ion Neutral Fluid Collisions

· Charge Exchange

· Momentum Exchange

• Histories Properties

– Array History

– Combo History

– Field History

– Log History

– Particle History

• References

3.1.1 Description Properties

The Description element holds basic user-supplied text information about the simulation. Most of the parameters aremost useful to advanced users who are creating and placing input files in the Examples directory of VSimComposer.The examples directory can be found in [VorpalInstallDirectory]ContentsExamples.

short description This string is the title of the example in the New->From Example selection.

description This is the description given in the window on the right side in the examples windowupon selecting an example.

long description This text block will be visible above the image in text-based setup, and is gener-ally used to give a description of what the simulation does, and what will happen when key parame-ters are modified.

16 Chapter 3. VSimComposer Visual Setup Reference

Page 21: VSim In Depth

VSim In Depth, Release 8.2.1

image The image parameter should give the name of a picture, located in the same directory as the inputfile, that will be given on the right hand side of the Editor pane in the Setup tab for text-based setup.Frequently, this image is used to illustrate key parameters such as dimensions of a physical structure.400 by 500 pixels is a good image size.

thumbnail This is the small image that is visible when you select an example file, located in the samedirectory as the input file. 250 x 250 pixels in a good image size.

version (not editable) The version of VSim used to create this example.

3.1.2 Constants Properties

The Constants element contains a set of pre-defined physical constants that can be used in other elements of thesimulation. Constants are just a number. You may add new constants by clicking the Add button under the ElementsTree while the Constants element (in the Elements Tree) is highlighted. For information on the Elements Tree see theimages on the setup-win-visual-setup-simulations page.

kind (not editable) The kind of constant; either a built-in kind or a User Defined kind.

description (only for User Defined constants) A descriptive name of the constant

value The value of the constant. This is the user-supplied value of the constant if kind = User Defined.Otherwise it is a non-editable value supplied by VSim.

3.1.3 Parameters Properties

The Parameters element is a location for evaluated, user defined, variables that can be used in other elements of thesimulation. A parameter is a mathematical combination of constants and other parameters. You may a new parameterAdd button under the Elements Tree.

kind (not editable) The kind of constant; a User Defined kind.

description A descriptive name of the parameter

expression This is the user-supplied expression that will be calculated to determine the value of theParameter. It can include any pre-defined Constants as well as real numbers and python functions.

value The VSim calculated value of the expression.

3.1.4 Basic Settings Properties

The Basic Settings element contains a group of property/value pairs that define the basic setup of the simulation.

surface meshing tolerance Determines the relative size at which small cells from a meshedgeometry surface are dropped. Set to 1.0 for simulations not containing any geometries.

cfl number If time step is set to zero, the time step is automatically calculated, and for EM simula-tions, is reduced proportionately with the cfl number. The cfl number is the ratio of time step toCourant limit.

time step If set to a value that is non-zero, this will be used as the simulation time step.

If set to zero, the time step is calculated for you based on a number of factors.

• If it is an ES simulation without particles, the time step is set to 1.0

• If it is an ES simulation with particles, the time step is set to the minimum of(2./{electron plasma frequency} or 1./(DLI*{electron thermal velocity}) where DLI =sqrt(1/DX^2+1/DY^2+1/DZ^2) in 3 dimensions.

3.1. VSimComposer Visual Setup 17

Page 22: VSim In Depth

VSim In Depth, Release 8.2.1

• If it is an EM simulation, time step is equal to the minimum of ES calculated time step or1.(LIGHTSPEED*DLI) and multiplied by the cfl number and surface meshing tolerance.

number of steps The number of time steps to run the simulation.

steps between dumps The number of time steps between sequential dumps of data to hdf5 formatfiles.

precision The precision of the real numbers in the simulation. For greater precision, use double.

• double

• float

length unit The unit of length used for setting parameters.

• meter

use GPU (if found) If a GPU is found, do calculations based on faster GPU updaters.

• false

verbosity The level of informative text to be output during the simulation run.

• information

• emergency

• alert

• critical

• error

• warning

• notice

• debug level 1

• debug level 2

• debug level 3

dimensionality Set to 1, 2, or 3 to indicate how many dimensions to run the simulation in.

• 1

• 2

• 3

Note: For cylindrical coordinates, only 2 dimensional electrostatic simulations are currently avail-able in visual setup.

grid spacing The spacing of the grid cells.

• uniform

reuse geometry files on restart This parameter is typically set to true. Due to a bug inmemory management on Windows 10 systems it should be set to false if working with complexgeometries.

coordinate system The type of coordinate system to work in.

18 Chapter 3. VSimComposer Visual Setup Reference

Page 23: VSim In Depth

VSim In Depth, Release 8.2.1

Note: For cylindrical coordinates, only 2 dimensional electrostatic simulations are currently avail-able in visual setup.

• cartesian

• cylindrical

field solver The field solver determines which equations will be used to calculate the fields.

Note: For cylindrical coordinates, only 2 dimensional electrostatic simulations are currently avail-able in visual setup.

• electrostatic

number of guard cells For information about guard cells see Cells and Dimen-sions

• electromagnetic

Cerenkov Filter Electromagnetic problems allow for the selection of a numericalCerenkov noise filter. These filters come in 4 varieties, or no filter.

none No Filter

weak Filters with a formula of (1-x)*(1+x). Should be used in problems with cavitiesor resonant structures.

medium Filters with a formula of (1-x)*(1+2x)(1-x). Should be used in problems withcavities or resonant structures.

strong Filters with a formula of (1-x). Should be used in problems with high numbersof realtivisitic particles.

extreme Filters with a formula of (1-x)*(1-x). Should be used in problems with highnumbers of realtivisitic particles.

Strong filters will execute the fastest, while medium will execute the slowest. These areall “Godfrey Filters”, which use additional curl-curl operations on the electric field toupdate the field at the next time step, removing short wavelengths. “Friedman Filters”are another type of filter that remove high frequency noise rather than short wavelengths.Please contact Tech-X if you wish to implement this class of filter.

periodic directions The directions of the simulation which should be modelled as periodic, ifany.

• no periodicity

• periodic x

• periodic y

• periodic z

• periodic x and y

• periodic x and z

• periodic y and z

• periodic x, y, and z

particles Whether or not to include particles in the simulation.

3.1. VSimComposer Visual Setup 19

Page 24: VSim In Depth

VSim In Depth, Release 8.2.1

• no particles

• include particles If particles are included in the simulation, the following 2 propertiesare used to help calculate the time step.

– estimated max electron density

– estimated min electron temperature (eV)

moving window Whether or not to use a moving window which allows the simulation window tomove at the speed of light in the chosen direction. Useful for simulations such as laser pulse orparticle beam moving at a velocity close to the speed of light.

• no moving window

• with moving window

– shift position fraction This determines the time at which the window will be-gin to move. The window will begin to move at a time equal to the shift position fractiontimes the size of the simulation grid divided by the speed of light.

– shift speed fraction This is the relativisitic 𝛽 factor which determines the speed𝑣 at which the window will move where 𝑣 = 𝛽𝑐.

3.1.5 Functions Properties

The Functions element is a location for writing user defined functions that can be used in simplifying the definition ofa SpaceTimeFunction. You have options to create your own User Defined function or use the built-in turn on function.The turn on function has the mathematical formula 𝐻(𝑡) * 0.5 * (1 − cos(𝜋𝑡/𝑇 )) * 𝐻(𝑇 − 𝑡) where 𝐻(𝑡) is theHeaviside Step Function.

kind (not editable) The kind of constant; a User Defined kind.

description A string describing the function.

arguments The arguments that are used in the expression. The function can contain any number ofarbitrary arguments and is not limited to the default values of x,y.

expression This is the user-supplied expression that is a function of the arguments given in the argu-ment property. It can include any pre-defined Constants, Parameters, or Functions, as well as realnumbers and python operator.

3.1.6 SpaceTimeFunctions Properties

The SpaceTimeFunctions element is a location for writing user defined functions that specifically depend on thespatial and temporal variables x, y, z, and t.

• User Defined. This option is deprecated. Use expression instead.

• expression This is the user-supplied expression that is a function of x,y,z, or t. It can include any pre-definedConstants, Parameters, or Functions, as well as real numbers.

• python

This space time function will allow access to a function defined in a python file to be used in place of a user-defined function.

name This is the name of the python function to be accessed. Note that the python file must be in thesame directory as the runspace.

• feedback

20 Chapter 3. VSimComposer Visual Setup Reference

Page 25: VSim In Depth

VSim In Depth, Release 8.2.1

This space time function is used to take the value from a history, and use that value in the next timestep, allowing feedback.

expression The initial value to be used in the feedback loop. This expression will be multipledfrom the value of the history in the previous output.

history The name of the history from which to take values, at this time only pseudo-potentialhistories are supported.

history goal The value of the history that should be obtained.

time constant Defines how quickly the feedback responsds to a difference in the measured anddesired value. If too small the measured value will oscillate near the desired value, if too large itwill take a long time to reach the desired value.

• chirpwavepulse

• cosineflattop

• cosineramp

• gaussian

• gaussianpulse

• gpuexpression

• halfsinepulse

• leakychannel

• planewavepulse

• radialcoschannel

• sineplanewave

• sum function This is the sum of two previously defined space time functions. Note that the functions usedmust be defined before their use in the sum function. Sum functions may be nested. For example a secondsum function used accepting a previously defined sum function in order to sum 3 or more space timefunctions.

sumFunction1 The first function to take the sum of.

sumFunction2 The second function to take the sum of.

• product function This is the product of two previously defined space time functions. Note that thefunctions used must be defined before their use in the product function. Product functions may be nested.For example a second product function used accepting a previously defined product function in order tomultiply 3 or more space time functions together.

prodFunction1 The first function to take the product of.

prodFunction2 The second function to take the product of.

3.1.7 Materials Properties

The Materials element stores information about any materials used in the simulation. To use one of VSim’s pre-defined materials, by highlight the Materials element, then switch from 3D View to Database in the Geometry View(see setup-win-visual-setup-simulations for a picture of the Geometry View). To add one of the pre-defined materialsfrom the table, highlight the material then press Add To Simulation button in upper right hand corner of the VsimComposer window. The material will now be listed under the Materials element. To access a wider selection ofmaterials you may load the emthermal.vmat file by right-clicking on the Materials element and selecting ImportMaterials. You may also import your own customized material (see Customizing Materials below).

3.1. VSimComposer Visual Setup 21

Page 26: VSim In Depth

VSim In Depth, Release 8.2.1

The editable properties of the materials are:

kind (not editable) The kind of material (eg dielectric, conductor, particle absorber, permeable, etc), asdefined in the .vmat file.

heat capacity The heat capacity of the material.

thermal conductivity The thermal conductivity of the material.

resistance The resistance of the material.

conductivity The conductivity of the material.

relative permittivity The relative permittivity of the material.

Customizing Materials

Custom materials properties can be created in a text editor and imported into VSim. To import a custom material:

1. Go to the “data” folder at the top level of the VSim installation directory. On Windows this will be in“Program Files\Tech-X (Win64)\VSim-8.1rc4\data\”. On Mac and Linux, there is no standard location.

2. Create a new text file that ends in the .vmat extension. For example: emthermalcustom.vmat.

3. Open the default materials file emthermal.vmat.

4. Copy a block from emthermal.vmat to emthermalcustom.vmat to use as a sample.

5. Edit the title and properties of the block as needed. For example:

<Material FreshWater><strings>kind = "dielectric"</strings><params>heat capacity = 4.184conductivity = 0.005relative permittivity = 80.4thermal conductivity = 0.6065</params>

</Material>

6. Save the new file

7. Back in VSim, Click on the Materials element in your simulation and then click Add>>Import Mate-rials. A file browser will appear with the data directory already open.

8. Select your custom vmat file. If you do not see your vmat file in the directory, navigate to where yousaved it.

9. The view will change to the Database tab and the materials added will be available here.

3.1.8 Geometries Properties

The Geometries element contains information about any geometries that are in the simulation. You can import a file,or create your own with CSG using the primative shapes described below.

22 Chapter 3. VSimComposer Visual Setup Reference

Page 27: VSim In Depth

VSim In Depth, Release 8.2.1

CSG

Constructive Solid Geometry can be used to build your own complex geometry

kind (not editable) Construction Group

tessellation The size of triangles used to construct the shape. This is a unitless number that is themaximum deviation of a facet from the curved surface divided by the diameter of the facet.

• Sphere

-kind (not editable) Sphere

-material The material to use for the shape. Chosen from a list of imported materials inyour simulation.

-radius The radius of the sphere.

-x position The location of the center of the sphere in the x direction.

-y position The location of the center of the sphere in the y direction.

-z position The location of the center of the sphere in the z direction.

• Box

-kind (not editable) Box

-material The material to use for the shape. Chosen from a list of imported materials inyour simulation.

-length The length of the box.

-height The height of the box.

-width The width of the box.

-x position The location of the center of the box base in the x direction.

-y position The location of the center of the box base in the y direction.

-z position The location of the center of the box base in the z direction.

-width direction x Set to 1 to make the width parameter of the box correspond to the xdirection.

-width direction y Set to 1 to make the width parameter of the box correspond to the ydirection.

-width direction z Set to 1 to make the width parameter of the box correspond to the zdirection.

-angle The angle of the box.

• Cylinder

-kind (not editable) Cylinder

-material The material to use for the shape. Chosen from a list of imported materials inyour simulation.

-length The length of the cylinder

-radius The radius of the cylinder

-x position The location of the base of the cylinder in the x direction

-y position The location of the base of the cylinder in the y direction

3.1. VSimComposer Visual Setup 23

Page 28: VSim In Depth

VSim In Depth, Release 8.2.1

-z position The location of the base of the cylinder in the z direction

-axis direction x Set to 1 to make the axial direction of the cylinder x, if set to -1 thelength parameter will extend in the negative direction

-axis direction y Set to 1 to make the axial direction of the cylinder y, if set to -1 thelength parameter will extend in the negative direction

-axis direction z Set to 1 to make the axial direction of the cylinder z, if set to -1 thelength parameter will extend in the negative direction

• Cone

-kind (not editable) Cone

-material The material to use for the shape. Chosen from a list of imported materials inyour simulation.

-height The height of the cone

-radius The radius of the base of the cone

-x position The location of the center of the cone base in the x direction

-y position The location of the center of the cone base in the y direction

-z position The location of the center of the cone base in the z direction

-axis direction x Set to 1 to make the axial direction of the cone x

-axis direction y Set to 1 to make the axial direction of the cone y

-axis direction z Set to 1 to make the axial direction of the cone z

• Torus

-kind (not editable) Torus

-material The material to use for the shape. Chosen from a list of imported materials inyour simulation.

-major radius The radius to the center of the torus

-minor radius The radius from the center of the torus to the outside of the torus

-x position The location of the center of the torus in the x direction

-y position The location of the center of the torus in the y direction

-z position The location of the center of the torus in the z direction

-axis direction x Set to 1 to make the axial direction of the torus x

-axis direction y Set to 1 to make the axial direction of the torus y

-axis direction z Set to 1 to make the axial direction of the torus z

• Pipe

-kind (not editable) Pipe

-material The material to use for the shape. Chosen from a list of imported materials inyour simulation.

-length The length of the pipe

-inner radius The inner radius of the pipe

-outer radius The outer radius of the pipe

24 Chapter 3. VSimComposer Visual Setup Reference

Page 29: VSim In Depth

VSim In Depth, Release 8.2.1

-x position The location of the base of the pipe in the x direction

-y position The location of the base of the pipe in the y direction

-z position The location of the base of the pipe in the z direction

-axis direction x Set to 1 to make the axial direction of the pipe x, if set to -1 the lengthparameter will extend in the negative direction

-axis direction y Set to 1 to make the axial direction of the pipe y, if set to -1 the lengthparameter will extend the negative direction

-axis direction z Set to 1 to make the axial direction of the pipe z, if set to -1 the lengthparameter will extend the negative direction

• TruncCone

-kind (not editable) TruncCone (Truncated Cone)

-material The material to use for the shape. Chosen from a list of imported materials inyour simulation

-height The height of the cone

-radius1 The radius of the base of the cone

-radius2 The radius of the top of the cone

-x position The location of the center of the cone base in the x direction

-y position The location of the center of the cone base in the y direction

-z position The location of the center of the cone base in the z direction

-axis direction x Set to 1 to make the axial direction of the cone x

-axis direction y Set to 1 to make the axial direction of the cone y

-axis direction z Set to 1 to make the axial direction of the cone z

• Wedge

-kind (not editable) Wedge

-material The material to use for the shape. Chosen from a list of imported materials inyour simulation.

-length1 One length of the wedge

-length2 The second length of the wedge

-height The height of the wedge

-width The width of the wedge. Extrudes the wedge from a 2 dimensional to 3 dimensionalobject

-x position The location of the base of the wedge in the x direction

-y position The location of the base of the wedge in the y direction

-z position The location of the base of the wedge in the z direction

-width direction x Set to 1 to apply the width parameter in the x direction

-width direction y Set to 1 to apply the width parameter in the y direction

-width direction z Set to 1 to apply the width parameter in the z direction

3.1. VSimComposer Visual Setup 25

Page 30: VSim In Depth

VSim In Depth, Release 8.2.1

Boolean Operations

CSG Primitives may be combined in three different ways

Subtract This will subtract the second selected primitive from the first selected primitive. Denoted by−.

Union This will combine the two primitives into a single object. For use if the combined object is set tobe a particle sink. Denoted by ∪.

Intersect This will leave only the volume of the two primitives that intersect as an object. Denotedby ∩.

Boolean operations may be nested, for example two primitives may be combined in a union, and then with a thirdprimitive in a second union. To combine primative shapes, you must first add two or more shapes to your simulation.Once your primative shapes are added, highlight the two shapes you wish to combine and right-click and selectBoolean Operation then the operation you wish to perform.

Imported

You can import a geometry of type .stl, .ply, .vtk, .stp, .step, or .p12 by right-clicking the Geometries element andselecting Import Geometries

kind (not editable)

• TriangSolid

• OceStepFromFile

filename The name and location of the imported file

scale A factor to scale the imported geometry by. (Not available in 8.0.)

tessellation The size of triangles used to construct the shape. This is a unitless number that is themaximum deviation of a facet from the curved surface divided by the diameter of the facet.

3.1.9 Grids Properties

kind (not editable) The kind of grid used

xMin The domain extent in the negative x-direction.

xMax The domain extent in the positive x-direction.

yMin The domain extent in the negative y-direction.

yMax The domain extent in the positive y-direction.

zMin The domain extent in the negative z-direction.

zMax The domain extent in the positive z-direction.

xCells The number of cells in the x-direction.

yCells The number of cells in the y-direction.

zCells The number of cells in the z-direction.

planeShift (in 1D or 2D) When working in 1 or 2 dimensions this selects the xy plane in which yoursimulation is defined.

lineShift (in 1D) When working in 1 dimension this selects the line (parallel to the x-axis) alongwhich your simulation is defined.

26 Chapter 3. VSimComposer Visual Setup Reference

Page 31: VSim In Depth

VSim In Depth, Release 8.2.1

3.1.10 Field Dynamics Properties

Fields Properties

Electric Field The electric field

Magnetic Field The magnetic field. Available in electromagnetic simulations

Current Density The current density field. Available in electromagnetic simulations. You may addmany current densities to your simulation.

External Magnetic Field (EM and Particles) The external magentic field. Available in elec-tromagnetic simulations with particles. An External Magnetic Field can be added by right-clickingFields and selecting External Magnetic Field under the Add Field option. You may add multipleExternal Magnetic Fields.

• b field specification The method for inputting the applied magnetic field.

– functional B Use a function to specify each component of the applied magnetic field.

Bx: The value of the applied magnetic field in the x-direction. Can be a constant, a param-eter, or a function of space and time.

By: The value of the applied magnetic field in the y-direction. Can be a constant, a param-eter, or a function of space and time.

Bz: The value of the applied magnetic field in the z-direction. Can be a constant, a param-eter, or a function of space and time.

– B from file Use a file to specify the applied magnetic field.

magnetic field file: The name of the file containing the data for the applied ma-gentic field.

Phi The electric potential field. Available in electrostatic simulations

Charge Density The charge density field. Available in electrostatic simulations

Background Charge Density The background charge density field. Available in electrostaticsimulations. You may add many Background Charge Densities to your simulation.

• expression The value of the background charge density field. Can be a constant, a param-eter, or a function of space and time.

Applied Magnetic Field The applied magnetic field. Availalble in electrostatic simulations withparticles.

• b field specification The method for inputting the applied magnetic field.

– functional B Use a function to specify each component of the applied magnetic field.

Bx: The value of the applied magnetic field in the x-direction. Can be a constant, aparameter, or a function of space and time.

By: The value of the applied magnetic field in the y-direction. Can be a constant, aparameter, or a function of space and time.

Bz: The value of the applied magnetic field in the z-direction. Can be a constant, aparameter, or a function of space and time.

– B from file Use a file to specify the applied magnetic field.

magnetic field file: The name of the file containing the data for the appliedmagentic field.

3.1. VSimComposer Visual Setup 27

Page 32: VSim In Depth

VSim In Depth, Release 8.2.1

Initial Condition

To add an Initial Condition to a field, right-click on the field and select Add FieldInitialCondition -> Initial Condition

kind (not editable) Inital Condition

expression The value of the initial condition. Can be assigned a Constant, Parameter, or SpaceTime-Function by right-clicking

component Can be 0, 1 or 2 for the first, second, or third component of the field.

FieldBoundaryConditions Properties

To add a Boundary Condition, right-click on FieldBoundaryConditions and select your choice from Add FieldBound-aryCondition. Your choices for dimensionality and field solver in the Basic Settings Properties element, will deterimewhich Boundary Condition are available to add to your simulation.

All possible types of Boundary Conditions include:

Dirichlet Use a Dirichlet boundary condition to set the value of the potential field, Phi, on the surface.

• value The value of the boundary condition. Can be assigned a Constant, Parameter, or Space-TimeFunction by right-clicking.

• surface The surface on which the Dirichlet boundary condition should be set.

– lower x The lower x boundary of the simulation domain

– lower y The lower y boundary of the simulation domain

– lower z The lower z boundary of the simulation domain

– upper x The upper x boundary of the simulation domain

– upper y The upper y boundary of the simulation domain

– upper z The upper z boundary of the simulation domain

– dirichlet index surface Use an index surface to specify a Dirichlet boundary condi-tion in a planar location that is not one of the simulation boundaries

lower indices: The lower indices of the surface

upper indices: The upper indices of the surface

– shape surface Use a shape surface to specify a Dirichlet boundary condition on the sur-face of a geometry in your simulation

object name: Choose from any pre-defined geometries in the simulation

Neumann Use a Neumann boundary condition to se the value of the derivative of the potential field, Phi,on the surface.

• value The value of the derivative. Can be assigned a Constant, Parameter, or SpaceTimeFunctionby right-clicking.

• surface The surface on which the Dirichlet boundary condition should be set.

– lower x The lower x boundary of the simulation domain

– lower y The lower y boundary of the simulation domain

– lower z The lower z boundary of the simulation domain

– upper x The upper x boundary of the simulation domain

28 Chapter 3. VSimComposer Visual Setup Reference

Page 33: VSim In Depth

VSim In Depth, Release 8.2.1

– upper y The upper y boundary of the simulation domain

– upper z The upper z boundary of the simulation domain

– neumann index surface Use an index surface to specify a Neuamnn boundary condi-tion in a planar location that is not one of the simulation boundaries

lower indices: The lower indices of the surface

upper indices: The upper indices of the surface

gradient direction Chooses the normal direction for the plane on which youare setting the boundary condition. A choice of 0 will create a yz plane (correspondingto normal vector pointing in the x direction). A choice of 1 will create a xz plane, anda choice of 2 will create a xy plane.

gradient multiplier Determines whether the plane is on the upper or lowerend of the simulation. Choose +1 for the lower end of the simulation domain (cor-resonding to a positive normal direction), and choose -1 for a plane on the upper endof the simulation domian (corresponding to a negative normal direction).

Boundary Launcher A boundary launcher will set the chosen field to the value given in theapplied field functions of space and time.

• field The field to which the boundary condition applies.

• applied fields The location and orientation of the applied fields. The location is chosen fromthe simulation domain boundaries. Depending on your choice for the applied field orientation(ie, the Value of the applied fields Property), you can set 2 of the following fields as a functionof space and time.

– Fx(x,y,z,t)

– Fy(x,y,z,t)

– Fz(x,y,z,t)

Coaxial Waveguide This is a port launcher boundary condition, with the functions defining it presetto create a coaxial cable. See the VSimEM example, coaxialloopantennaexample for a demonstra-tion of it’s use. For proper operation a physical coaxial cable must be constructed in Geometries tomatch the specified cable here.

• inner radius The radius of the inner conductor

• outer radius The radius of the outer conductor

• frequency The frequency of the signal

• voltage The voltage of the signal

• relative permittivity The relative permittivity of the dielectric insulator

• start time The time at which to turn on the coaxial waveguide

• stop time The time at which to turn off the coaxial waveguide

• turn on time The amount of time to bring the coaxial waveguide up to full power. Typically2.5 periods of the carried signal

• coaxial waveguide surface The simulation domain boundary from which the coaxialwaveguide enters the simulation. Depending on the selected boundary 2 of the following 3options are allowed

– X-center coordinate The center of the coaxial waveguide in X

– Y-center coordinate The center of the coaxial waveguide in Y

3.1. VSimComposer Visual Setup 29

Page 34: VSim In Depth

VSim In Depth, Release 8.2.1

– Z-center coordinate The center of the coaxial waveguide in Z

Matched Absorbing Layer A boundary condition that adds a Matched Absorbing Layer (MAL)to the specified face. A matched absorbing layer uses isotropic electric and magnetic dampingprofiles to absorb the inicident wave. This is unlike a PML (Perfectly Matched Layer) which usesthe same electric and magnetic damping profiles, but is anisotropic. MAL boundaries are more stableas an anisotropic boundary condition can become unstable when the incident wave has a non-zeroimaginary part to its normal wavenumber (e.g., fringing fields from nearby structure, or particlesentering the layer)

• thickness The thickness of the MAL in number of cells

• surface The simulation domain surface on which the MAL boundary condition should be set.

– lower x

– lower y

– lower z

– upper x

– upper y

– upper z

Open A boundary condition that is “open” allowing EM waves to freely exit. This is a Mur1 absorbingboundary condition. The open boundary condition works best for waves normal to the surface.

• surface The simulation domain surface on which the open boundary condition should be set.

– lower x

– lower y

– lower z

– upper x

– upper y

– upper z

Perfect Electric Conductor A boundary condition that sets parallel components of the electricfield to zero. For example, if the PEC boundary condition is added to the lower x surface, the y andz components of the electric field are set to zero.

• surface The simulation domain surface on which the PEC boundary condition should be set.

– lower x

– lower y

– lower z

– upper x

– upper y

– upper z

Perfect Magnetic Conductor A boundary condition that sets parallel components of the mag-netic field to zero. For example, if the PMC boundary condition is added to the lower x surface, they and z components of the magnetic field are set to zero.

• surface The simulation domain surface on which the PEC boundary condition should be set.

1 Gerrit Mur, IEEE Transactions on Electromagnetic Compatibility, Vol. EMC-23, No. 4, November 1981

30 Chapter 3. VSimComposer Visual Setup Reference

Page 35: VSim In Depth

VSim In Depth, Release 8.2.1

– lower x

– lower y

– lower z

– upper x

– upper y

– upper z

Perfectly Matched Layer A perfectly matched layer (PML) boundary condition. PML’s provideboundary conditions for the Yee algorithm that allows outgoing waves to leave without reflections(ideally).

• thickness The thickness of the PML in number of cells

• sigma

The strength of the pml conductivity. Typically 3.0 or 5.0*LIGHTSPEED/DL, where DL isthe cell size in the normal direction.

• exponent The exponent in the pml conductivity. Typically 1.5.

• surface The simulation domain surface on which the MAL boundary condition should be set.

– lower x

– lower y

– lower z

– upper x

– upper y

– upper z

Port A Port boundary condition is a tuned phase-velocity boundary condition. It can be used as an openor outgoing boundary condition with waves travelling at exactly the specified phase velocity will exitthe simulation with no reflection at all. Waves traveling at other phase velocities will partially exitand partially reflect, with a power reflection coefficient of 𝜌 = (𝑣𝑝,𝑤𝑎𝑣𝑒−𝑣𝑝,𝑏𝑐)

2/(𝑣𝑝,𝑤𝑎𝑣𝑒+𝑣𝑝,𝑏𝑐)2.

• phase velocity The phase velocity tuning parameter in meters/second.

• surface The simulation domain surface on which the MAL boundary condition should be set.

– lower x

– lower y

– lower z

– upper x

– upper y

– upper z

Port Launcher A Port Launcher boundary condition will add a Port boundary condition to thechosen surface as well as setting the D field to the value given in the applied field functionsof space and time.

• phase velocity The phase velocity tuning parameter in meters/second.

3.1. VSimComposer Visual Setup 31

Page 36: VSim In Depth

VSim In Depth, Release 8.2.1

• applied fields The location and orientation of the applied fields. The location is chosen fromthe simulation domain boundaries. Depending on your choice for the applied field orientation,you can set 2 of the following fields as a function of space and time.

– Dx(x,y,z,t)

– Dy(x,y,z,t)

– Dz(x,y,z,t)

Rectangular Waveguide This is a port launcher boundary condition, with the functions definingit preset to create a rectangular waveguide. See the VSimEM example, rectangular waveguide foran demonstration of it’s use. For proper operation a physical waveguide must be constructed inGeometries at the location specifed here.

• frequency The frequency of the signal

• voltage The voltage of the signal

• relative permittivity The relative permittivity of the dielectric insulator

• start time The time at which to turn on the rectangular waveguide

• stop time The time at which to turn off the rectangular waveguide

• turn on time The amount of time to bring the rectangular waveguide up to full power. If thistime is set to less than 2.5 periods of the carried signal, it will automatically be increased to 2.5periods

• waveguide surface The simulation domain boundary from which the rectangular waveguideenters the simulation Depending on the selected boundary 2 of the following 3 options areallowed, as well as the polarization direction

– X-center coordinate The center of the rectangular waveguide in X

– Y-center coordinate The center of the rectangular waveguide in Y

– Z-center coordinate The center of the rectangular waveguide in Z

– polarization direction The polarization direction of the waveguide. This will corre-spond to the height parameter of the waveguide.

• waveguide type

The type of waveguide used. Several commonly used waveguides are included, as well asthe option to define your own.

• User Defined

– height The height of the waveguide. This will correspond to the polarization direction of thewaveguide

– width The width of the waveguide.

• Included Waveguides

The eight predefined waveguides are WR-90, WR-340, WR-284, WR-229, WR-187, WR-159, WR-137, and WR-112.

WG equivalent (not-editable) The RCSC designation of this waveguide type

standard frequency range (not-editable) The frequencies over which thiswaveguide operates. A warning will be given if an operating frequency is given outsidethis range.

32 Chapter 3. VSimComposer Visual Setup Reference

Page 37: VSim In Depth

VSim In Depth, Release 8.2.1

height (not-editable) The height of the waveguide. This will correspond to the polar-ization direction of the waveguide

width (not-editable) The width of the waveguide.

CurrentDistributions Properties

CurrentDistributions are available for electromagnetic simulations

Dipole Current A dipole current is a current source centered around the user specified location andgoing ±1 cell around the specified location.

• kind (not editable) Dipole Current

• expression The expression used to define the dipole. Can be assigned a Constant, Parameter,or SpaceTimeFunction by right-clicking. This should be either a constant or a function of timeonly.

• component The component of the current density field to be set by the expression.

• coordinate The physical location (in meters) that the dipole current should be set.

Distributed Current A distributed current sets the values of the current density in the specifiedvolume. Only available in 3 dimensional simulations.

• kind (not editable) Distributed Current

• J0(x,y,z,t) If any, the expression for the current source in the x-direction

• J1(x,y,z,t) If any, the expression for the current source in the y-direction

• J2(x,y,z,t) If any, the expression for the current source in the z-direction

• volume

– xMin The domain extent in the negative x-direction

– xMax The domain extent in the positive x-direction

– yMin The domain extent in the negative y-direction

– yMax The domain extent in the positive y-direction

– zMin The domain extent in the negative z-direction

– zMax The domain extent in the positive z-direction

PoissonSolver Properties

PoissonSolver is available for electrostatic simulations

kind (not editable) Poisson Solver

relative permittivity Function giving the relative permittivity.

solver VSim allows the use of the direct solver, SuperLU, or one of the current choices for iterativesolvers.

• SuperLU Use the SuperLU solver.

• conjugate gradient An iterative solver for symmetric systems. For all iterative solversthere are the following parameters:

– tolerance The size of the error vector for stopping the iteration to solution.

3.1. VSimComposer Visual Setup 33

Page 38: VSim In Depth

VSim In Depth, Release 8.2.1

– max iterations The maximum number of iterations allowed to achieve the solu-tion. Anything above 30 is questionable.

– convergence metric This is described in the AztecOO user guide, p. 17, currentlyhere. Metrics are one of

– r0 Use the ratio of the L2 norms of the residual and the initial residual.

– rhs Use the ratio of the L2 norms of the residual and the right-hand side.

– Anorm Use the ratio of the L2 norm of the residual and the maximum absolute row sumof the matrix (L-infinity norm).

– noscaled Use the ratio of the L2 norm of the residual.

– sol Use the ratio of the maximum component of the residual and the sum of (L-infinitynorm of the matrix times the maximum absolute component of the first iterate to thesolution + the maximum absolute component of the right-hand side).

preconditioner

• no preconditioner

• multigrid Multigrid has a large number of parameters. In most cases, the defaults are good. Ifone is using particles, the linear solve often does not matter in overall timing.

– mg defaults Only the SA option is allowed for now as it works well for symmetric matri-ces.

* SA

– maximum levels The maximum number of levels of multigrid smoother application beforedoing a direct solve on the smaller problem. For highly parallel problems this should belimited to 3-4 to minimize communication time.

– smoother type The smoother to apply at each multigrid level. The default is a good choice,but the user may try other smoothers to achieve best solving times. The choices are:

* Gauss Seidel

* symmetric variable block Gauss Seidel

* Jacobi

* Chebyshev

* Aztec

– smoother sweeps The number of times to apply the smoother at each multigrid level. Agood choice is 3, but the user may try other values to achieve best solving times.

– when to smooth Generally one wants to smooth both. The before and after choices areprovided to the user to try other values to achieve best solving times.

* both

* before

* after

– coarse type The type of solver to use at the coarsest level.

* Jacobi

* KLU

34 Chapter 3. VSimComposer Visual Setup Reference

Page 39: VSim In Depth

VSim In Depth, Release 8.2.1

– damping factor Damping factor for smoothed aggregation. The default is a good choice.Users may try other values to achieve best solving times.

– threshold This determines the multigrid aggregation at each level.

– increase or decrease If set to increasing, level 0 will correspond to the finest level.If set to decreasing, max levels - 1 will correspond to the finest level. Should not affectconvergence. The choices are:

* increasing

* decreasing

3.1.11 Particle Dynamics Properties

To view the Particle Dynamics element in the Element Tree, the include particles option must be selected under BasicSettings Properties

KineticParticles

Charged Particles

Charged Particles can be used to define any kinetic particle with given mass and charge.

kind (not editable) Charged Particles

nominal density A positive value suggesting the nominal density for the particles. This will beused in conjunction with the weight setting to compute the density, weights, and number of particlesin a macro particle for your kinetic particles.

mass The mass of a single real particle.

charge The charge of a single real particle.

particle weights Whether to use constant or variable weight particles

• variable weights The weights of the macroparticles can vary throughout the simulation

• constant weights The weights of the macroparticles are constant throughout the simulation

particle dynamics Whether to use relativistic or non-relativistic particles

• relativistic Use the relativistic particle pushing algorithm to update the particle positions andvelocities by including a gamma term.

• non-relativistic Use the non-relativistic particle pushing algorithm to update the particlepositions and velocities.

weight setting Whether to use computed weights or explicitly set weights.

• computed weights Let VSim calculate your macroparticle weights for you based on the num-ber of macroparticles per cell you specify as well as the nominal density. The weights arecalculated such that the number of particles in a macro particle is equal to the nominalDensity* cellVolume / macroparticles per cell

– macroparticles per cell The number of macroparticles per cell

• explicitly set weights Declare the number of particles in a macro particle explicitly

– particles per macroparticle The number of particles in a macroparticle

3.1. VSimComposer Visual Setup 35

Page 40: VSim In Depth

VSim In Depth, Release 8.2.1

Electrons

Electrons are pre-defined to have a charge = -1.602176487e-19 and a mass = 9.10938215e-31

kind (not editable) Electrons

nominal density A positive value suggesting the nominal density for the particles. This will beused in conjunction with the weight setting to compute the density, weights, and number of particlesin a macro particle for your kinetic particles.

particle weights Whether to use constant or variable weight particles

• variable weights The weights of the macroparticles can vary throughout the simulation

• constant weights The weights of the macroparticles are constant throughout the simulation

particle dynamics Whether to use relativistic or non-relativistic particles

• relativistic Use the relativistic particle pushing algorithm to update the particle positions andvelocities by including a gamma term.

• non-relativistic Use the non-relativistic particle pushing algorithm to update the particlepositions and velocities.

weight setting Whether to use computed weights or explicitly set weights.

• computed weights Let VSim calculate your macroparticle weights for you based on the num-ber of macroparticles per cell you specify as well as the nominal density. The weights arecalculated such that the number of particles in a macro particle is equal to the nominalDensity* cellVolume / macroparticles per cell

– macroparticles per cell The number of macroparticles per cell

• explicitly set weights Declare the number of particles in a macro particle explicitly

– particles per macroparticle The number of particles in a macroparticle

Secondary Electron Emitter

Secondary electrons can be emitted from a electron species, charged particle species, or neutral particle species,. Theycan then be emitted into a seperate electron species, or into the same electron species.

emitter type

• secondary electron emitter This emitter is for use on simulation boundaries.

– particle boundary condition The particle boundary condition to emitsecondary electrons from. It must be of the type Boundary Absorb and Save. Ifselected as a particle boundary condition of a different species, particles from thatspecies will emit into the electron species.

– material The material for computing the secondary electron yield. One of “cop-per” or “stainless”.

– suppresion energy Suppress emission of secondary electrons unless the emit-ted energy is greater than this number. Useful if electrons are emitted in a regionwhere the local electric field would push them back into the wall in the same timestep. In this case, set to a large number.

• interior secondary electron emitter

This emitter is for use with particle boundary conditions internal to the simula-tion space.

36 Chapter 3. VSimComposer Visual Setup Reference

Page 41: VSim In Depth

VSim In Depth, Release 8.2.1

– particle boundary condition The particle boundary condition to emitsecondary electrons from. It must be of the type Interior Absorb and Save orCut Cell Absorb and Save. It can be from a different particle species, which willcause incident particles of that species to sputter as the neutral particle species.

– material The material for computing the secondary electron yield. One of“copper” or “stainless”.

– suppresion energy Suppress emission of secondary electrons unless theemitted energy is greater than this number. Useful if electrons are emitted ina region where the local electric field would push them back into the wall in thesame time step. In this case, set to a large number.

– emitted energy The energy of the emitted electrons if constant weight parti-cles are used

– SEY(E) A function to define the secondary electron yield, where E is the impacenergy of the impacting elctron.

• constant probability secondary electron emitter This emitter willemit secondary electrons according to a user defined probability.

– particle boundary condition The particle boundary condition to emitsecondary electrons from. It must be of the type Boundary Absorb and Save.

– emission probability The probability that a secondary electron is emitted,between 0.0 and 1.0.

Neutral Particles

Neutral Particles of the gas kinds listed below are pre-defined with the appropriate charge and mass values.

kind (not editable) Neutral Particles

nominal density A positive value suggesting the nominal density for the particles. This will beused in conjunction with the weight setting to compute the density, weights, and number of particlesin a macro particle for your kinetic particles.

particle weights Whether to use constant or variable weight particles

• variable weights The weights of the macroparticles can vary throughout the simulation

• constant weights The weights of the macroparticles are constant throughout the simulation

particle dynamics Whether to use relativistic or non-relativistic particles

• relativistic Use the relativistic particle pushing algorithm to update the particle positions andvelocities by including a gamma term.

• non-relativistic Use the non-relativistic particle pushing algorithm to update the particlepositions and velocities.

weight setting Whether to use computed weights or explicitly set weights.

• computed weights Let VSim calculate your macroparticle weights for you based on the num-ber of macroparticles per cell you specify as well as the nominal density. The weights arecalculated such that the number of particles in a macro particle is equal to the nominalDensity* cellVolume / macroparticles per cell

– macroparticles per cell The number of macroparticles per cell

• explicitly set weights Declare the number of particles in a macro particle explicitly

3.1. VSimComposer Visual Setup 37

Page 42: VSim In Depth

VSim In Depth, Release 8.2.1

– particles per macroparticle The number of particles in a macroparticle

gas kind The type of gas

• H: Atomic Hydrogen

• H2: Molecular Hydrogen

• He: Helium

• Ar: Argon

• Xe: Xenon

Sputter Emitter

Neutral particle types may sputter from other particle species.

emitter type

The type of emitter to use, either a sputter emitter or interior sputter emitter

sputter emitter

This type of emitter should be used when emitting off a simulation boundary particleboundary condition.

• particle boundary condition The particle boundary condition to sputter parti-cles from. It must be of the type Boundary Absorb and Save. It can be a particle bound-ary condition from a different particle species, which will cause incident particles of thatspecies to sputter as the neutral particle species.

• material properties This will determine the type of atom that is sputtered.

• sputtered velocity sigma The standard deviation of the velocity distribution ofemitted particles.

interior sputter emitter

This emitter is for use when emitting off an interior particle boundary condition.

• particle boundary condition The particle boundary condition to sputterparticles from. It must be of the type Interior Absorb and Save or Cut Cell Absorband Save. It can be a particle boundary condition from a different particle species,which will cause incident particles of that species to sputter as the neutral particlespecies.

• material properties This will determine the type of atom that is sputtered.

• sputtered velocity sigma The standard deviation of the velocity distribu-tion of emitted particles.

• emission axis The axis along which particles are to be emitted, 0 for the 0thdimension, 1 for the 1st dimension or 2 for the 2nd dimension.

• emission direction Set to either positive or negative, this is the direction in whichparticles are emitted.

• emission coordinate The coordinate at which particles are actually emitted. Effec-tively this is an offset from the position of the particle boundary condition.

38 Chapter 3. VSimComposer Visual Setup Reference

Page 43: VSim In Depth

VSim In Depth, Release 8.2.1

Particle Loader Properties

All kinetic particles have access to the same type of particle loader

load density Whether to define the density of loaded particles by macroparticles or physical parti-cles.

relative density Use a function defining the density of loaded particles in macroparticles.

physical density Use a function defining the density of loaded particles in physical particles.

particle load placement Whether to used a bit-reversed or grid defined placement of macropar-ticles in each cell.

• grid Place particles equidistant on the grid lines of the simulation. Useful for starting simu-lations “cold”

• macro particles per direction A vector describing the number of macroparticlesto load per cell on each axis.

• bit-reversed Places particles according to a bit-reversed algorithm.

load duration Whether to only load the particles at the beginning of the simulation or repeatedly.

• initialize only Particles will only be loaded at the beginning of the simulation.

• repeat loading Particles will be loaded according to the paramters below.

• start time The time at which to start loading particles.

• stop time The time at which to stop loading particles.

• load after initialization Loading will repeat in all cells during the loading period.- load upon shift Load particles into cells brought into the simulation by a moving win-dow.

velocity distribution The velocity components of particles as they are loaded

• u0 The velocity in the 0th dimension.

• u1 The velocity in the 1st dimension.

• u2 The velocity in the 2nd dimension.

volume The volume in which to load particles - cartesian 3d slab - cartesian 2d slab -cylindrical 2d slab

Settable Flux Emitter Properties

All particle types may emit from a settable flux emitter.

flux setting

• emission current density If specified the current desnity of the emitter is to be specified.

• emission flux density If specified the flux density is to be specified, which will be con-verted to current density internally.

beam emitter

• start time The time at which particles are to start emitting.

• stop time The time at which particles are to stop emitting.

• mean velocity A vector for the average velocity in the 0th, 1st, and 2nd dimensions of theemitted particles.

3.1. VSimComposer Visual Setup 39

Page 44: VSim In Depth

VSim In Depth, Release 8.2.1

• thermal velocity The standard deviation of particle velocities in the 0th, 1st and 2nd dimen-sions.

surface The surface to emit particles off of, either a simulation boundary or geometry.

• lower x The lower x simulation boundary.

• lower y The lower y simulation boundary.

• lower z The lower z simulation boundary.

• upper x The upper x simulation boundary.

• upper y The upper y simulation boundary.

• upper z The upper z simulation boundary.

shape emitter

• object name The name of the geometry to emit off of.

• mask function A function that can be used to tailor particle emission off of the object, if it isdesired to mask certain parts of the object.

• emission offset The distance away from the object that emitted particles are placed.

• localize velocity directions to shape If set to true, the axial directions for veloc-ities given in the mean velocity and thermal velocity parameters will be localized to the shape.

TestParticleSpecies Properties

Field Scaling Electrons

These are a special type of electron used in testing. Most notably they consist of only one physical particle permacroparticle. They are in fact given a variable weight, however this weight is used to track if the particles have beencreated via secondary emission. Each particle also has a scaling value, allowing for multiple voltage levels to existin the simulation simultaneously. Since there is only one physical particle per macroparticle these particles will havenegligible effect on the simulation.

The primary use of these particles is to scan a structure for multipacting resonances across a number of power levelsat the same time.

Field scaling electrons make use of the same particle boundary conditions and secondary emitters as regular electrons,but have their own type of loader and secondary emitter.

Field Scaling Electron Loader

This particle loader is very similar to a standard particle species loader, with some notable exceptions.

load density Only the relative density of particles may be specified, as this is the same as the phys-ical density.

• physical density This will specify the number of particles per cell.

particle load placement At this time particles may only be loaded according to a bit-reversedalgorithm.

load duration Whether to only load the particles at the beginning of the simulation or repeatedly.

• initialize only Particles will only be loaded at the beginning of the simulation.

• repeat loading Particles will be loaded according to the paramters below.

40 Chapter 3. VSimComposer Visual Setup Reference

Page 45: VSim In Depth

VSim In Depth, Release 8.2.1

– start time The time at which to start loading particles.

– stop time The time at which to stop loading particles.

– load after initialization Loading will repeat in all cells during the loadingperiod.

– load upon shift Load particles into cells brought into the simulation by a movingwindow.

scaling factor This will determine the minimum value, maximum value, and scaling factor appliedto the field scaling electrons. So for example with a minimum value of 10, and a scaling factor of 3,that individual electron is charged to 30V.

• minimum scaling factor The minimum voltage of the particles loaded.

• maximum scaling factor The maximum voltage of the particles loaded.

• number of scale factors The number of scale factors, or steps, between the mini-mum scaling factor and maximum scaling factor.

volume The volume in which to load particles

• cartesian 3d slab

• cartesian 2d slab

• cylindrical 2d slab

ParticleBoundaryCondition Properties

Particle boundary conditions may be set to any particle type. If a particle boundary condition is not set on a simulationboundary, it is automatically set to absorbing.

Boundary Absorb and Save

This type of boundary condition will absorb incident particles and save them for other uses, such as histories orsecondary emission

volume The simulation boundary over which to apply this condition

Interior Absorb and Save

This type of boundary condition will absorb incident particles and save them for use with histories or secondaryemission. It may be set to an internal volume of the simulation space.

volume Depending on simulation properties this will be either a - cartesian 2D slab -cylindrical 2D slab - cartesian 3D slab

Cut-Cell Absorb and Save

This type of boundary condition will absorb incident particles and save them for other uses, such as histories orsecondary emission. It may be applied to geometries. Note that in VSim8.1 ony one Cut-Cell Absorb and Saveboundary condition may be used per simulation.

volume

• object name The name of the geometry over which to apply this condition.

Absorbing

This type of particle boundary condition will absorb incident particles. It will not save any data from them, so theymay not be used in histories or secondary emitters.

volume

3.1. VSimComposer Visual Setup 41

Page 46: VSim In Depth

VSim In Depth, Release 8.2.1

• lower x slab

• lower y slab

• lower z slab

• upper x slab

• upper y slab

• upper z slab

• cartesian 3d slab

• cylindrical 2d slab

• index 3d slab

Reflecting

This type of particle boundary condition will reflect particles back into the simulation space. It may only be appliedon simulation boundaries.

volume

• lower x slab

• lower y slab

• lower z slab

• upper x slab

• upper y slab

• upper z slab

• lower r slab

• upper r slab

BackgroundGases Properties

kind (not editable) Neutral Background Gas

gas temperature (K) The temperature of the neutral background gas in Kelvin

gas kind The type of gas

• H: Atomic Hydrogen

• H2: Molecular Hydrogen

• He: Helium

• Ar: Argon

• Xe: Xenon

volume This volume value will change depending on your dimensionality and coordinate system.

• xMin The minimum x position of the background gas

• xMax The maximum x position of the background gas

• yMin The minimum y position of the background gas

• yMax The maximum y position of the background gas

42 Chapter 3. VSimComposer Visual Setup Reference

Page 47: VSim In Depth

VSim In Depth, Release 8.2.1

• zMin The minimum z position of the background gas

• zMax The maximum z position of the background gas

initial gas density Whether to use a constant or variable gas density

• constant gas density Use a constant value for the density

• density The value of the density of the neutral gas per cubic meter

• variable gas density Use a value of the density that varies spatially.

• density The value of the density of the neutral gas per cubic meter

Collisions Properties

Kinetic particles can have elastic, excitation, and ionization collisions with background gases.

Electron Neutral Fluid Collisions

To include a collision process, right-click on the Electron Neutral Fluid Collision in the element tree and choose AddCollisionProcess to choose one of either Elastic, Excitation, or Ionization.

• neutral gas Select the neutral gas to use in the collision. The drop down will automatically populate withavailable pre-defined BackgroundGases elements.

• impact particles Select the electron particles to use in the collision. The drop down will automaticallypopulate with availalbe pre-defined KineticParticles of kind = Electrons.

Elastic

kind (not editable) Elastic

cross section type The cross section for the collision must be specified. You can choose whetherto use built in cross sections, cross sections from the Evaluated Electron Data Library (EEDL) orby specifying your own user defined cross sections in a text file.

• user defined cross section User provided cross-section data provided in a text file. Formore information on the format of the file, please see montecarlointeractions-interactions-oafunc

– cross section data file The name of the file containing the corss section data

• product distribution The type of scattering

– isotropic

– Vahedi-Surendra

Excitation

kind (not editable) Excitation

cross section type The cross section for the collision must be specified. You can choose whetherto use built in cross sections, cross sections from the Evaluated Electron Data Library (EEDL) orby specifying your own user defined cross sections in a text file.

3.1. VSimComposer Visual Setup 43

Page 48: VSim In Depth

VSim In Depth, Release 8.2.1

• user defined cross section User provided cross-section data provided in a textfile. For more information on the format of the file, please see montecarlointeractions-interactions-oafunc

• cross section data file The name of the file containing the corss section data

• product distribution The type of scattering

– isotropic

– Vahedi-Surendra

Ionization

kind (not editable) Ionization

product electrons The resultant electrons from the impact ionization collision

product ions The resultant ions from the impact ionization collision

cross section type The cross section for the collision must be specified. You can choose whetherto use built in cross sections, cross sections from the Evaluated Electron Data Library (EEDL) orby specifying your own user defined cross sections in a text file.

• user defined cross section User provided cross-section data provided in a textfile. For more information on the format of the file, please see montecarlointeractions-interactions-oafunc

• cross section data file The name of the file containing the corss section data

• product distribution The type of scattering

– isotropic

– Vahedi-Surendra

Ion Neutral Fluid Collisions

To include a collision process, right-click on the Ion Neutral Fluid Collision in the element tree and choose AddCollisionProcess to choose one of either Charge Exchange or Momentum Exchange.

neutral gas Select the neutral gas to use in the collision. The drop down will automatically populatewith available pre-defined BackgroundGases elements.

impact particles Select the charged particles to use in the collision. The drop down will automat-ically populate with availalbe pre-defined KineticParticles of kind = Charged Particles.

Charge Exchange

kind (not editable) Charge Exchange

cross section type The cross section for the collision must be specified. You can choose whetherto use built in cross sections, cross sections from the Evaluated Electron Data Library (EEDL) orby specifying your own user defined cross sections in a text file.

• built in The built in collisions utilize existing internal collision cross-section data.

• user defined cross section User provided cross-section data provided in a textfile. For more information on the format of the file, please see montecarlointeractions-interactions-oafunc

44 Chapter 3. VSimComposer Visual Setup Reference

Page 49: VSim In Depth

VSim In Depth, Release 8.2.1

• cross section data file The name of the file containing the corss section data

• product distribution The type of scattering

– backward

Momentum Exchange

kind (not editable) Momentum Exchange

cross section type The cross section for the collision must be specified. You can choose whetherto use built in cross sections, cross sections from the Evaluated Electron Data Library (EEDL) orby specifying your own user defined cross sections in a text file.

• built in The built in collisions utilize existing internal collision cross-section data.

• user defined cross section User provided cross-section data provided in a textfile. For more information on the format of the file, please see montecarlointeractions-interactions-oafunc

cross section data file The name of the file containing the corss section data

• product distribution The type of scattering

isotropic

3.1.12 Histories Properties

Array History

An Array History will output an array of data for each time-step.

Far-Field Observation Only available in electromagnetic simulations

• kind (not editable) Far-Field Observation

• time delay The simulation time at which the history begins recording

• duration The simulation time length during which the history records

• number of time points

• Kirchhoff sphere radius The radius of the Kirchhoff sphere

• number of polar angles The number of polar angles represented on the Kirchhoffsphere

• number of azimuthal angles The number of azimuthal angles represented on theKirchhoff shpere

• number of line integral segments The number of integration points around thefar-field sphere

• Kirchhoff sphere center The center of the Kirchhoff sphere

Far-Field Box Data Only available in electromagnetic simulations

• kind (not editable) Far-Field Box Data

• start time The simulation time at which the history begins recording

• end time The simulation time at which the history ends recording

3.1. VSimComposer Visual Setup 45

Page 50: VSim In Depth

VSim In Depth, Release 8.2.1

• volume The volume to use for the box

• cartesian 3d slab

– xMin The minimum x position of the box

– xMax The maximum x position of the box

– yMin The minimum y position of the box

– yMax The maximum y position of the box

– zMin The minimum z position of the box

– zMax The maximum z position of the box

Particle Momentum Calculate the total momentum for a particular set of particles in the whole sim-ulation domain. All three components of the momentum are recorded. Thus, for some simulationsin 1D or 2D, some components of the momentum may always be zero.

• kind (not editable) Particle Momentum

• particles Select any of the previously defined KineticParticles in your simulation.

Combo History

Combo Histories are used to do operations on other histories. The operation is done at every time step and theresulting values are recorded as a new history. The output will be a 1D array of the value vs time.

Binary Combination History A Binary Combination History can be used to combine any twoField or Particle histories.

• kind (not editable) Binary Combination History

• history 1 Select one previously defined Field or Particle History

• history 2 Select one previously defined Field or Particle History

• history1 coefficient A multiplying factor on the first history

• history2 coefficient A multiplying factor on the second history

• combination Which operation to use for combining the histories

– add (history1coefficient*history 1) + (history2 coefficient*history 2)

– subtract (history1 coefficient*history 1) - (history2 coefficient*history 2)

– multiply (history1 coefficient*history 1) * (history2 coefficient*history 2)

– divide (history1 coefficient*history 1) / (history2 coefficient*history 2)

Field History

Field Histories record on a per time-step basis. Field histories are used to measure quantities such as the value orenergy of the field at a location. The output will be a 1D array of the value vs time.

Electric Field Energy Calculate the total energy of the electric field in the specified volume.

• kind (not editable) Electric Field Energy

• volume The region over which to calculate the field energy

– simulation region Use the entire simulation domain

– index 3d slab A user-defined volume based on cell indices

46 Chapter 3. VSimComposer Visual Setup Reference

Page 51: VSim In Depth

VSim In Depth, Release 8.2.1

• lower indices The lower indices of the volume

• upper indices The upper indices of the volume

EM Field Energy Calculate the total energy of the electromagnetic field in the specified volume.Only available in electromagnetic simulations.

• kind (not editable) EM Field Energy

• volume The region over which to calculate the field energy

– simulation region Use the entire simulation domain

– index 3d slab A user-defined volume based on cell indices

• lower indices The lower indices of the volume

• upper indices The upper indices of the volume

• shape A volume based on a previously defined geometry

• object name Select from a previously defined geometry

Magnetic Field Energy Calculate the total energy of the magnetic field in the specified volume.

• kind (not editable) Magnetic Field Energy

• volume The region over which to calculate the field energy

– simulation region Use the entire simulation domain

– index 3d slab A user-defined volume based on cell indices

• lower indices The lower indices of the volume

• upper indices The upper indices of the volume

Field at Position Record the specified field at the specified coordinates. All components of thefield are recorded into an array.

• kind (not editable) Field at Position

• field Select the desired field

• coordinate0 The position coordinate in the 0th dimension. x in cartesian coordinates, z incylindrical

• coordinate1 The position coordinate in the 1st dimension. y in cartesian coordinates, r incylindrical

• coordinate2 The position coordinate in the 2nd dimension. z in cartesian coordinates

Poynting Flux Calculates the integrated Poynting vector (energy flux) through the area defined bythe min and max values

• kind (not editable) Poynting Vector

• surface The plane to use

• yz

– offset The x offset from zero, in meters

– yMin The location of the y minimum, in meters

– yMax The location of the y maximum, in meters

– zMin The location of the z minimum, in meters

– zMax The location of the z maximum, in meters

3.1. VSimComposer Visual Setup 47

Page 52: VSim In Depth

VSim In Depth, Release 8.2.1

• xz

– offset The y offset from zero, in meters

– xMin The location of the x minimum, in meters

– xMax The location of the x maximum, in meters

– zMin The location of the z minimum, in meters

– zMax The location of the z maximum, in meters

• xy

– offset The z offset from zero, in meters

– xMin The location of the x minimum, in meters

– xMax The location of the x maximum, in meters

– yMin The location of the y minimum, in meters

– yMax The location of the y maximum, in meters

Pseudo-potential This option is deprecated. Use ‘Pseudo-potential at Coordinates’ or‘pseudo-potential at Indices’ instead.

• kind (not editable) Pseudo-potential

• start indices The indices of the cells for the starting location

• end indices The indices of the cells for the ending location

Pseudo-potential at Coordinates Calculates the pseudo-potential difference, in Volts, be-tween two points. The start point would correspond to the measure point, while the end point wouldcorrespond to the reference

• kind (not editable) Pseudo-potential

• start coordinate 0 The coordinate of the start point in the 0th dimension

• start coordinate 1 The coordinate of the start point in the 1st dimension

• start coordinate 2 The coordinate of the start point in the 2nd dimension

• end coordinate 0 The coordinate of the end point in the 0th dimension

• end coordinate 1 The coordinate of the end point in the 1st dimension

• end coordinate 2 The coordinate of the end point in the 2nd dimension

Pseudo-potential at Indices Calculates the pseudo-potential difference, in Volts, betweentwo points, specified by grid index.

• kind (not editable) Pseudo-potential

• description A description of the potential difference

• start indices The indices of the cells for the starting location

• end indices The indices of the cells for the ending location

Log History

A Log History will record data on a per-event basis rather than at each time step.

Absorbed Particle Log Record information about each and every particle that strikes a chosenabsorbing surface. The output will be a 1D array of the value.

48 Chapter 3. VSimComposer Visual Setup Reference

Page 53: VSim In Depth

VSim In Depth, Release 8.2.1

• kind (not editable) Absorbed Particle Log

• particle absorber Select the previously defined particle absorbing boundary condition.This must be a ParticleBoundaryCondition that can Save

• particle quantity What information about the particle is to be recorded. For vector-like quantities (position, velocity, and weight), you must select which component of thevector you wish to record in component option (0->x, 1->y, 2->z).

– particle time The time the particle strikes the absorber

– particle position The position of the particle when it is absorbed

– particle velocity The velocity of the particle when it is absorbed

– particle weight The weight of the particle when it is absorbed

– particle energy The total energy of all the particles that are absorbed

– particle current The total current of all the particles that are absorbed

Particle History

Particle Histories record on a per time-step basis. Particle histories are used to measure quantities such as the totalnumber of particles in a simulation at each step, or the current absorbed at chosen absorbing surface at each step. Theoutput will be a 1D array of the value vs time.

Absorbed Particle Current Calculates the absorbed current on a specified particle absorber.

• kind (not editable) Absorbed Particle Current

• particle absorber Select the previously defined particle absorbing boundary condition.This must be a ParticleBoundaryCondition that can Save

Absorbed Particle Energy Calculates the energy absorbed on a specified particle absorber.

• kind (not editable) Absorbed Particle Energy

• particle absorber Select the previously defined particle absorbing boundary condition.This must be a ParticleBoundaryCondition that can Save

Emitted Current Records the emitted current from the specified particle emitter

• kind (not editable) Emitted Current

• particle emitter Select the previously defined particle emitting boundary condition.

Number of Macroparticles Calculates the total number of macroparticles in the simulation do-main for the specified KineticParticle

• kind (not editable) Number of Macroparticles

• particles Select the name of the previously defined KineticParticles

Number of Physical Particles Calculates the total number of real particles in the simulationdomain for the specified KineticParticle

• kind (not editable) Number of Physical Particles

• particles Select the name of the previously defined KineticParticles

Particle Energy Calculates the total energy in the simulation domain for the specified KineticPar-ticle

• kind (not editable) Particle Energy

3.1. VSimComposer Visual Setup 49

Page 54: VSim In Depth

VSim In Depth, Release 8.2.1

• particles Select the name of the previously defined KineticParticles

3.1.13 References

50 Chapter 3. VSimComposer Visual Setup Reference

Page 55: VSim In Depth

CHAPTER

FOUR

TEXT-BASED INPUT FILE OVERVIEW

4.1 Accessing the Input File

4.1.1 Accessing the Input File

To access the input file in a simulation, navigate to the Setup tab and click the View Input File button, which is outlinedin red in the below figure.

This opens the Input File view as shown in the below figure. Note that you can return to the Parameters view byclicking the Parameters View button, which is circled in red.

For a more detailed description of simulation input files, see Tutorials.

51

Page 56: VSim In Depth

VSim In Depth, Release 8.2.1

4.2 Input File Structure

4.2.1 Input File Elements

The most basic elements of the simulation process, which are discussed in vsimcomposer-intro and considered prereq-uisites for this section, are creating, running, and visualizing a simulation. Here we will examine the basic conceptswithin an input file (a file with the .pre extension), which contains more detailed information than the Key InputParameters view in the VSimComposer Setup tab, and is by default not exposed to the user.

A Vorpal input file contains a hierarchical set of code blocks and variables that describe the structure and behavior ofa simulation model. From this hierarchical view, there are two levels of blocks in the input file: top level blocks andnested blocks. How these blocks work together to specify the simulation model, along with the variable values thatcontrol the simulation activity, are briefly introduced in this section.

In addition to the various blocks, there are global variables, like the time step, that are required in the input file.

An input file can be simplified by the introduction of macros. A macro provides a way to substitute a code snippetfrom an another file or location into the input file.

Elements of an input file:

• Comments

• User Variables

• Global Variables

• Top Level Blocks

• Nested Blocks

• Parameters (including vectors of parameters)

• Macros

52 Chapter 4. Text-based Input File Overview

Page 57: VSim In Depth

VSim In Depth, Release 8.2.1

# This is a comment

# These are user defined variables$ NX = 5$ NY = 10

# These are global variablesdimension = 3floattype = doubledt = 1.e-9nsteps = 100dumpPeriodicity = 10

# This is a top level block<Grid compGrid>

numCells = [NX NY NZ] #This is a vector of parameterslengths = [LX LY LZ]startPositions = [XSTART YSTART ZSTART]

</Grid>

# These are nested blocks<GridBoundary cylinder>

kind = funcGridBndrydmFrac = DM_FRAC # This is a parameter<STFunc function>kind = expressionexpression = H(RADIUS^2 - x^2 - y^2) - 0.6

</STFunc></GridBoundary>

# This is a macro which will bring in the correct blocks to create# particle sinks around the edges of the entire domain.absorbingBox(NX, NY, NZ)

4.2.2 Comments

You can enter comments in either of two ways:

• Following a pound sign (#) either on a new line or a continuation of a current line

• Between the opening and closing comment tags <Comment> </Comment>

Note: Tech-X recommends that you always update your comments when you make changes to an inputfile. The reasoning behind a change may become unclear if you do not provide comments that explainwhy you made the change. Input files with old, out-of-date comments are difficult to work with.

4.2.3 User Variables

Variables are defined by assignment, similar to many other programming languages. For example, to define a givenvariable with an expression, the syntax is:

4.2. Input File Structure 53

Page 58: VSim In Depth

VSim In Depth, Release 8.2.1

$VARIABLE = EXP

where VARIABLE is the name of the variable and EXP is any valid expression. See Expression Evaluation for details.

The python prepocessor will not try to substitute a variable on the left hand side of an equal sign =. For example, thefollowing code snippet:

$charge = 1.6e-19charge = charge

results in:

charge = 1.6e-19

Each line defining a variable must begin with a dollar sign ($)

4.2.4 Global Variables

Global Variables: Those variables declared outside of any specific block that control various aspects of thesimulation, including, for example, the size of a time step, the number of steps to take, how often to dump datafiles, and whether we wish to sort particles.

List of All Global Variables

Global variables define basic values to be used by Vorpal throughout the simulation described by the input file. Someglobal variables, such as dt, can only appear once in an input file. Global variables that are defined only once perinput file are denoted as singletons. In the description of the various global variables below, it is noted if a given globalvariable is required or not.

floattype (string, required): variable that defines the precision of real numbers in the simulation. For greaterprecision, use the value double, otherwise use the option float.

Example Use of floattype:

floattype = double

dimension (integer, required): variable that defines the dimensionality (1D, 2D, or 3D) of the simulation. Thevariable indicates how many dimensions this simulation will use. If running on the command line, the -dimcommand line parameter overrides this variable.

Example use of dimension:

dimension = 2

dt (real, required): time step size to use in the simulation. When choosing the step size for your simulation, youmust consider stability requirements. For example, for electromagnetic simulations, you should specify a stepsize that satisfies the Courant condition. If running on the command line, you can override the dt variable usingthe -dt command line option. be defined in an input file.

Example use of dt:

dt = 1.49731212265e-16

nsteps (integer, required): number of steps to take. (In the case of a restart, nsteps is the number of additionalsteps). If running on the command line, this can be overridden with the -n command line parameter.

54 Chapter 4. Text-based Input File Overview

Page 59: VSim In Depth

VSim In Depth, Release 8.2.1

Example use of nsteps:

nsteps = 22277

dumpPeriodicity (integer, optional): how often to dump the data; indicates data is to be dumped wheneverthe time step has increased by this amount. If running on the command line, the command line parameter -doverrides this variable.

Note: One of either dumpPeriodcity or dumpSteps must be in the file.

Example use of dumpPeriodicity:

dumpPeriodicity = 222

dumpSteps (integer, optional): alternative to dumpPeriodicity allowing an irregular specification of times steps inwhich to dump. Steps should be in increasing order, but do not need to be evenly spaced.

Note: One of either dumpPeriodcity or dumpSteps must be in the file.

Example use of dumpSteps:

dumpSteps = [4000, 8000, 8020, 8040, 8060, 8080, 8100]

Second example use of dumpSteps:

$ DUMPSTEPS = range(1, 9800, 2000) + range(9800, 10000, 10)dumpSteps = DUMPSTEPS

maxcellxing (integer, optional): In particle simulations in which the particles could ordinarily cross more thanone cell in a time step and cause out-of-bounds memory access (such as can happen in electrostatic simulationswith non-relativistic dynamics), you can impose a velocity limit to prevent the out-of-bounds memory accessfrom occurring by using the maxcellxing variable. E.g., maxcellxing = 1 will limit the particle velocity sothat the particle cannot cross more than one cell per step. That is, if for any direction i, velocity_i * dt > dx_i,then the velocity is reduced in magnitude so that velocity_i * dt<= dx_i for all i. Since imposing a velocity limitintroduces error into the simulation, for cases in which you must use the velocity limit for a significant numberof particles, you should lower the time step for the simulation.

Example Use of maxcellxing:

maxcellxing = 1

sortPtcls (boolean, default = true): Specifies whether or not you want Vorpal to sort the particles based on analgorithm that intelligently selects the time step at which to sort. This can affect performance and may be aparameter that you want to examine on your own for its effect on performance.

Example Use of sortPtcls:

sortPtcls = false

dnSortMin (integer, optional): This parameter is used to instruct Vorpal what is the minimum number of time stepsbefore sorting of the particles. This allows sorting to be deterministic and thus repeatable.

Example Use of dnSortMin:

4.2. Input File Structure 55

Page 60: VSim In Depth

VSim In Depth, Release 8.2.1

dnSortMin = 50

dnSortMax (integer, optional): This parameter is used to instruct Vorpal what is the maximum number of timesteps before sorting of the particles. This allows sorting to be deterministic and thus repeatable.

Example Use of dnSortMax:

dnSortMax = 50

useGridBndryRestore (boolean, default = true): switch to control the method for obtaining grid boundaryinformation on restarts. The default (true) is to input boundary information from the dump files. Setting thisswitch to false means that the grid boundary information is re-calculated, which can be computationally moreintensive.

Example use of useGridBndryRestore:

useGridBndryRestore = true

useHistoryRestore (boolean, default = true): The default(true), restores histories so that the dump andrestart yields the same result as simply continuing simulation (also important for feedback); if false, treat historydump file as if empty, and append data only with no regard for previous data

Example use of useHistoryRestore:

useHistoryRestore = true

copyHistoryAtEachDump (boolean, default = true): The default(true), copies the History file at each dumpin a HistoryOld file before appending the new history data. This is a safety measure in case the history file getscorrupted. If false, the data is simply appended to the History file, without creating a back up (or copied) file.

Example of use of copyHistoryAtEachDump:

copyHistoryAtEachDump = false

stepPrintPeriodicity (integer, default = 1): how often to print out the “Taking step n at clock time...” mes-sage as the simulation runs. By default, this option is 1 and the message is printed every step. If this option is0, the message will never be printed. If this option is 10, the message will be printed for every tenth step. Thisoption is useful for reducing the amount of output of simulations that run many time steps.

Example use of stepPrintPeriodicity:

stepPrintPeriodicity = 100

timingAnalysisPeriodicity (integer, optional): how often to calculate (and print) rough timing diagnosticsto evaluate the speed of a simulation (the output is repeated in a single line format that can be grepped out andimported into a spreadsheet). This is especially useful for analyzing load-balancing and parallel scaling.

By default, this option is -1, and no timings are calculated; if 0, timings are printed out for the entire simulation.If a positive integer, timings will be printed out periodically. For example, if this option is 1000, the timing foreach set of 1000 time-steps will be printed out (as well as a summary for the entire simulation).

Timings are calculated from wallclock-time and will be affected by other activity. The timing resolution variesfrom system to system; short times (much less than a second) should probably not be trusted.

Example use of timingAnalysisPeriodicity:

timingAnalysisPeriodicity = 1000

56 Chapter 4. Text-based Input File Overview

Page 61: VSim In Depth

VSim In Depth, Release 8.2.1

Global Variables Specific To Moving Windows

The moving window feature allows the simulation window to move at the speed of light in the chosen direction. Thisfeature is used to reduce the size of the simulation box while following the physics phenomenon of interest such as alaser pulse or a particle beam propagating at a velocity close to the speed of light.

downShiftDir (integer):

control variable for the moving window option that sets the direction of the moving window. If thedownShiftDir parameter is not specified or set to -1, Vorpal does not use the moving window.Set to a number between 0 and dimension to cause a down shift (moving window) in that direction.

• null (If no value specified, Vorpal does not use the moving window.)

• -1 (If -1 is specified, Vorpal does not use the moving window)

• 0 (x direction)

• 1 (y direction)

• 2 (z direction)

downShiftPos (real): distance at which Vorpal should activate the moving window feature. Vorpal calculatesthe time equal to this distance divided by the speed of light to determine when to turn on the moving window.The downShiftPos parameter may be set to a variable such as DSHFTPOS, which has been assigned a realnumber value such as 0.95**LX*, where LX is the length of the grid along the x axis.

OAFunc shiftSpeed (block): function (of one variable) that returns the velocity of the moving window (in m.s-1) as a function of time. When using kind = expression in an OAFunc block x is the default variable, touse t instead, specify variable = t in the OAFunc block [see expression-oafunc]. You can still use x butbe aware that x represents the time in this case.

Example Moving Window Code

# Moving window# Shift along direction 0downShiftDir = 0# Start shifting at t = DSHFTPOS/(speed of light)downShiftPos = DSHFTPOS

<OAFunc shiftSpeed>kind = expressionexpression = LIGHTSPEED *(BETA - ALPHA *t)variable = t

</OAFunc>

Global Variables from Inside a Block

It is possible to declare a global variable in VSim. This is done by first defining the variable, then declaring it global.For example:

<Block>$ X = 4$ global X

</Block>

Will cause the variable X to be equal to 4 outside of the Block. It is important to note that the variable must be defined,and declared global on seperate lines. For example $ global X = 4 will not define X as a global variable with value 4.

4.2. Input File Structure 57

Page 62: VSim In Depth

VSim In Depth, Release 8.2.1

4.2.5 Top Level Blocks

Those blocks that appear at the top level of the input file block hierarchy define the basic characteristics for thesimulation as a whole and for other blocks that will be used in the simulation. Some top level blocks, such as Grid,Decomp, and SumRhoJ, can appear only once in an input file; blocks that are defined only once per input file aredenoted as singletons. Also, every simulation must without exception contain a Grid and Decomp block.

Other blocks, such as Species, can be used as many times as needed in the input file. You will find detaileddescriptions of blocks in later sections of the VSim Reference. You will find examples for using the blocks in VSim InDepth.

Top level blocks include:

Grid (singleton): determines the simulation size and relationship of physical coordinate to cell indices. See grid.Note that Grid is required in every input file block.

Decomp (singleton): determines the domain decomposition and periodicity. See decomp. Note that Decomp isrequired in every input file block.

SumRhoJ (singleton): defines the properties of the charge- and current-density 4-vector field. See sumrhoj.

GridBoundary: defines any embedded boundaries. See gridboundary.

EmField: defines any electromagnetic fields. See emfield.

ComboEmField: defines any combinations of electromagnetic fields. See comboemfield.

Fluid: defines any fluids. See fluid.

Species: defines any particles. See species.

MonteCarloInteractions: defines any random processes that may occur between different objects in the sim-ulation such as collisions or ionization processes. See montecarlointeractions.

MultiField: defines general field blocks whose parameter and variable values may be adjusted during the simula-tion. See multifield.

ScalarDepositor: alternate method to deposit charge from charged particles in a simulation into a depField.See scalardepositor.

VectorDepositor: alternate method to deposit current from charged particles in a simulation into a depField.See vectordepositor.

History: used to record data from a simulation over time. See history.

Block Layout

Input blocks are used to create simulation objects. The block is enclosed by opening and closing tags such as:

<Grid globalGrid>...

</Grid>

The tag determines:

• object type: indicated by an initial capital letter, for example, Grid

• object name: indicated by an initial lowercase letter, for example, globalGrid

58 Chapter 4. Text-based Input File Overview

Page 63: VSim In Depth

VSim In Depth, Release 8.2.1

You use the object name to refer to the object in other input blocks. For example, in the input block for a particleobject, you may refer to the name of the electromagnetic field object.

Input blocks can be nested. For example, input blocks for boundary conditions are nested within the input block foran electromagnetic field.

Note: Tech-X recommends that when you nest input blocks, use an appropriate amount of indentation to improve thereadability of the input file.

4.2.6 Nested Blocks

While top level blocks are used at the top of the input file block hierarchy, nested blocks are included within othercode blocks. For example, a Vorpal Species block can contain a ParticleSource block that describes how thatSpecies is inserted into the simulation. The ParticleSource code block is, therefore, said to be nested within theSpecies block. Nested blocks are noted in the descriptions of those blocks that can contain them.

A nested block applies only to the block that contains it. For example, you can use a BoundaryCondition blockto affect an EmField. You could then specify different boundary conditions for a second EmField block.

Similarly, particle species can contain other objects. For example, you can use ParticleSource andParticleSink blocks in Species to describe where particles are to be placed into and removed from the simula-tion. By using these blocks’ kind parameters you describe how the emitting or absorption is to be accomplished. Youare not limited to defining blocks using a single level of nesting. The ParticleSources contained inside a particlespecies like <Species electrons> also contain a Vorpal STFunc block. Taken all together, these blocks denotethe space-time function used to describe particle emission.

Example of Nested Blocks

<Species electrons>kind = relBorischarge = -1.6022e-19mass = 9.109e-31emField = myEmField# Nominal density and particles per cell at that densitynominalDensity = 4.41204859999e+22nomPtclsPerCell = 2.# Particles loaded in a ramp<ParticleSource stepSrc1>kind = bitRevDensSrcdensity = 4.41204859999e+22lowerBounds = [2.5e-07 -2.5e-05 -2.5e-05]upperBounds = [5e-06 2.5e-05 2.5e-05]doShiftLoad = 1vbar = [0. 0. 0.]vsig = [0. 0. 0.]# Unit probability<STFunc macroDensFunc>

kind = constantFuncamplitude = 1.

</STFunc></ParticleSource><ParticleSource stepSrc2>kind = bitRevDensSrcdensity = 4.41204859999e+22

4.2. Input File Structure 59

Page 64: VSim In Depth

VSim In Depth, Release 8.2.1

lowerBounds = [5e-07 -2.5e-05 -2.5e-05]upperBounds = [5e-06 2.5e-05 2.5e-05]doShiftLoad = 1vbar = [0. 0. 0.]vsig = [0. 0. 0.]# Unit probability<STFunc macroDensFunc>

kind = constantFuncamplitude = 1.

</STFunc></ParticleSource># Particles out left are removed<ParticleSink leftAbsorber>kind = absorberminDim = 1lowerBounds = [-1 -1 -1]upperBounds = [ 0 21 21]

</ParticleSink># Particles out right are removed<ParticleSink rightAbsorber>kind = absorberminDim = 1lowerBounds = [40 -1 -1]upperBounds = [41 21 21]

</ParticleSink></Species>

4.2.7 Parameters

Parameters can be integers, floating-point numbers, or text strings.

The format of the parameter value determines the type of parameter. For example:

• x = 10 indicates an integer

• x = 10.0 indicates a floating-point number

• x = ten indicates a text string

Some parameters accept any text string (within reason). Other parameters accept only a choice of text strings.

If VSim can parse a value, such as 42, as an integer, it will do so. If VSim cannot parse the value as an integer, it willattempt to parse it as a floating-point number – for example, any of the following:

42.3.141591.60217646e-19

If VSim cannot parse the value as either an integer or a floating-point number, it will parse the value as a string of text,for example, either of the following:

4o. (4 and lowercase O) or4O (4 and uppercase O).

Use a decimal point to specify a floating point number. You must write floating-point numbers with a decimal point sothat they will not be interpreted as integers. If you want to assign a floating-point value to an integer parameter, makesure you write it as 3. (with a decimal point .) rather than only the numeral 3 (without a decimal point). If you write

60 Chapter 4. Text-based Input File Overview

Page 65: VSim In Depth

VSim In Depth, Release 8.2.1

the number as an integer (without the decimal point), VSim will interpret it as an integer. This will likely produceunexpected results.

Check that you have correctly defined parameter values. If you incorrectly define a parameter that has a default value,the default value will be used and potentially produce unsatisfactory results. If you incorrectly define a parameter thatdoes not have a default value, the computational engine may crash, fail to compute the physics of the simulation, orignore the incorrectly defined parameter and give you unsatisfactory results.

Do not specify a parameter twice. If you do, the second occurrence of the parameter in the processed input file(produced from the input file) will be used. Although parameters and input blocks can be defined in many differentsequences, if you follow the recommendations in this guide, you should not have a problem with specifying parameterstwice.

Vectors of Parameters

Vectors of parameters are enclosed by brackets [ ] with white space used as separators. For example:

• x = [10 10 10] indicates a vector of integers

• x = [10. 10. 10.] indicates a vector of floats

4.2.8 Macros

A macro is a mechanism to abstract complex input file sequences into (parameterized) tokens. In its simplest form, amacro provides a way to substitute a code snippet from an input file:

VSim contains a number of pre-defined macros that are used throughout the example input files available through theVSimComposer interface. You may find the VSim macros to be helpful in your own simulations.

The ability to use certain macros in VSim is tied to the particluar VSim license in use.

Please see Basics of Macro Definition and Usage of macros for more detail

4.3 In Depth

4.3.1 Implementation Kind

Most Vorpal blocks, including both top level and nested blocks, have several algorithms from which you may chooseby specifying a parameter named kind. For example, an EmField may be modeled as a Yee field, a direct sum field,a constant field, or any of several other types. You use the kind parameter to select a particular implementation. Eachblock description in this manual lists the available kind parameter settings for that block.

Note: If you don’t see the implementation kind you need for a given field block, you may wish to considerlearning to use the MultiField blocks to define your own implementation. In addition, Tech-X Pro-fessional Services is available on a contractual basis to create custom implementations and simulations.Contact Tech-X at [email protected] to discuss consulting options.

Example Blocks Specifying kinds

4.3. In Depth 61

Page 66: VSim In Depth

VSim In Depth, Release 8.2.1

<EmField myExternalField>kind = funcEmField<STFunc E0>kind = expressionexpression = EX_1 * cos(K_PE * x) * H( DRIVE_TIME - t )

</STFunc></EmField>

4.3.2 Scoping and Evaluation

Variables in VSim are scoped. This means that the effect of a variable’s definition is confined to the macro or block inwhich that variable is defined. Whenever VSim enters a macro or a new input file block, it enters a new scope.

In the case in which VARIABLE is defined in multiple scopes, Vorpal ignores the previously defined VARIABLE forthe duration of the current scope. In the case in which VARIABLE is defined more than once in the current scope, thenew value overrides the previous value defined in the current scope.

This scope is closed once VSim leaves the block or macro. That is, the variable’s definition no longer has an effectonce VSim has used the variable’s value in the macro or block where it was defined and then proceeded to a differentblock or macro. Scoping allows the next block or macro to be free to redefine the value of the variable for its ownpurposes.

4.3.3 Expression Evaluation

VSim evaluates expressions by interpreting them as Python expressions. Python expressions are composed of tokens.A token is a single element of an expression, such as a constant, identifier, or operation. The preprocessor breaks theexpression string into individual tokens then performs recursive substitution on each token. Once a token is no longerfound to be substitutable, the preprocessor tries to evaluate it as a Python expression. The result of this evaluation willthen be used as the value of this token. All the token values are then concatenated and again evaluated as a Pythonexpression. This result will then be assigned to the symbol.

Tokenizing, the act of breaking a string into tokens, is performed following the lexical rules of Python. This meansthat white spaces are used to delimit tokens, but are otherwise entirely ignored.

Note: A string within matched quotes is treated as a single token with the matching quotes removed.

The processed input files generated by VSim are sensitive to white spaces; as a result, VSim has to re-introduce whitespaces in the translation process. By default, tokens are joined without any white spaces. However, if both tokens areof type string, then a white space is introduced. Also, tokens inside an array (delineated by [ and ]) are delimited bya white space.

See the Python documentation on the official Python website at http://www.python.org for more information aboutPython expressions.

62 Chapter 4. Text-based Input File Overview

Page 67: VSim In Depth

CHAPTER

FIVE

TUTORIALS

5.1 Physics Tutorials

5.1.1 Your First Simulation - Electromagnetic Plane Wave

Putting it all Together

In this section we will take the basic concepts of VSim simulations to examine an input file. The goal of this lesson isto demonstrate how to start generating your own input files for custom simulations.

To define the simulation, you first create an input file. This input file has to be validated before it can be run.

We begin by examining a simple input file, emPlaneWave.pre,that simulates an electromagnetic plane wave.

1. Open VSimComposer either by double-clicking the VSimComposer icon on your desktop or work surface, orgoing to your application menu and selecting Tech-X–>VSim 8.1–>VSimComposer.

2. Select New –> From Example... from the File menu at the top of the VSimComposer window as shown inSelect New -> From Example... from the File menu.

3. Expand VSim for Basic Physics -> Textbook Examples (Text-based setup) as shown in Select VSim for BasicPhysics examples.

4. Select Electromagnetic Plane Wave (Text-based setup) as shown in Select Electromagnetic Plane Wave.

After you choose Electromagnetic Plane Wave (Text-based setup), VSimComposer prompts you to choose a filenameand directory into which VSimComposer will place the input file and other files associated with running the Electro-magnetic Plane Wave example. You may create either a new folder at this time or navigate to an existing directory.

5. Create a new folder named emPlaneWave into which VSimComposer will place a copy of emPlaneWaveT.pre as shown in Create a New Directory named emPlaneWave

VSimComposer opens the Setup window showing some easy-to-edit parameters and an image and description asshown in emPlaneWave.pre in the VSimComposer Editor

The complete text for the emPlaneWave.pre file is available later in this guide.

The emPlaneWave.pre file contains these five major sections:

1. variable definition

2. simulation parameter definition

3. grid definition

4. decomposition definition

5. electromagnetic field definition

63

Page 68: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 5.1: Select New -> From Example... from the File menu

64 Chapter 5. Tutorials

Page 69: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 5.2: Select VSim for Basic Physics examples

5.1. Physics Tutorials 65

Page 70: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 5.3: Select Electromagnetic Plane Wave

66 Chapter 5. Tutorials

Page 71: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 5.4: Create a New Directory named emPlaneWave

5.1. Physics Tutorials 67

Page 72: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 5.5: emPlaneWave.pre in the VSimComposer Editor

68 Chapter 5. Tutorials

Page 73: VSim In Depth

VSim In Depth, Release 8.2.1

XSim definition

The first section of a file usually is the XSim block where descriptions, images, and analysis scripts are defined for theparticular simulation. These parameters are used in VSimComposer to provide detail about the example.

<XSim emPlaneWaveT>shortDescription = "Electromagnetic Plane Wave (Text-based setup)"description = "An electromagnetic plane wave launched into vacuum."longDescription = "An electromagnetic plane wave with a sinusoidal amplitude is

→˓launched from the left side (x=0). The transverse (y, z) boundary conditions are→˓periodic."image = "emPlaneWaveT.png"thumbnail = "emPlaneWaveTTn.png"canChangeDt = truecanChangeNdim = trueanalyzers = []

</XSim>

Input Parameter Definitions

Next we typically find primary global parameters. This simple input file defines parameters for the number of cells inthe simulation grid along the x axis (NX), y axis (NY), and z axis (NZ). Our simulation has 50 cells along the x axis, 50cells along the y axis, and 50 cells along the z axis as well as dimensionality (NDIM), length along the x axis (LX), yaxis (LY), and z axis (LZ) and wavelengths (WAVELENGTHS).

Also defined are the number of steps to run and the frequency at which to write the output to files. TheTIMESTEP_FACTOR helps to limit the time step to obey the CFL condition.

By changing the parameters, you can quickly change aspects of the simulation.

############ Primary variables (defined in terms of constants)###########

# Default dimensionality$ NDIM = 2# Number of grid cells$ NX = 50$ NY = 50$ NZ = 50# Lengths$ LX = 2.0e-05$ LY = 2.0e-05$ LZ = 2.0e-05# Number (5) of wavelengths in the box$ WAVELENGTHS = 5.

$ NSTEPS = 100$ DUMPPERIOD = 10# Time step is this factor times the CFL limiting time step$ TIMESTEP_FACTOR = .995

5.1. Physics Tutorials 69

Page 74: VSim In Depth

VSim In Depth, Release 8.2.1

Key Input Parameters

Following the declaration of key input parameters, XVar’s will be given to allow the modification of primary parame-ters from the parameters window in VSimComposer. These are not necessary to run the simulation, but do allow foreasy reconfiguration of the primary parameters.

XVar’s also allow for minimum and maximum values to be assigned to the variable.

############ Exposed variables###########

# Number of cells in the x direction<XVar NDIM>

description = "Number of dimensions for the simulation"min = 1max = 3

</XVar>

# Time step is this factor times the CFL limiting time step<XVar TIMESTEP_FACTOR>

description = "Time step is this factor times the CFL limiting time step"</XVar>

# Number of wavelengths in the box<XVar WAVELENGTHS>

description = "Number of wavelengths in the x direction"min = 1.

</XVar>

# Number of cells in the x direction<XVar NX>

description = "Number of cells in the x direction"min = 10

</XVar>

# Number of cells in the y direction<XVar NY>

description = "Number of cells in the y direction"min = 10

</XVar>

# Number of cells in the z direction<XVar NZ>

description = "Number of cells in the z direction"min = 10

</XVar>

# Number of time steps to run the simulation<XVar NSTEPS>

description = "Number of time steps to run the simulation"min = 10

</XVar>

# Number of timesteps between memory dumps<XVar DUMPPERIOD>

70 Chapter 5. Tutorials

Page 75: VSim In Depth

VSim In Depth, Release 8.2.1

description = "Number of time steps between memory dumps"</XVar>

Import Values and Macros

Next, necessary macros will be imported so that functions from them may be called in the input file

############ Import values and macros###########

$ import mathphys$ import yee$ import requiredBlocks$ import verbosity # Provide verbosity level parameters

Secondary Variable Definition

After importing necessary macros, the secondary variables are defined. These are defined from primary variables andfundamental constants (e.g. LIGHTSPEED)

############ Define variables in lines starting with $ for later use###########

$ DX = LX/NX$ DY = LY/NY$ DZ = LZ/NZ$ DT = standardTimeStep(1.,TIMESTEP_FACTOR)

$ LAMBDA = LX/WAVELENGTHS$ FREQUENCY = LIGHTSPEED/LAMBDA$ OMEGA = 2. * PI * FREQUENCY$ PERIOD = 1/FREQUENCY$ TURNONTIME = PERIOD

Simulation Parameter Definition

Following the definition of the variables, the input file defines the top-level simulation parameters.

This basic input file defines five simulation parameters:

• dimension

• floattype

• dt

• nsteps

• dumpPeriodicity

5.1. Physics Tutorials 71

Page 76: VSim In Depth

VSim In Depth, Release 8.2.1

############ Define the basic simulation parameters###########

# The dimension and precision of the simulationdimension = NDIMfloattype = double

# Time step of integration and number of stepsdt = DTnsteps =NSTEPS

# Dump output into an HDF5 file every 5 time stepsdumpPeriodicity = DUMPPERIOD

Grid Definition

Following the definition of the top-level simulation parameters (global variables), the input file defines the grid.

The grid is the first in a series of input blocks defined by tags. The opening tag for the grid is:

<Grid globalGrid>

and the closing tag for the grid is:

</Grid>

Note: Each simulation can have only one grid.

############ Define the grid: the physical problem and the number of cells###########

$ XBGN = 0.$ YBGN = 0.$ ZBGN = 0.<Grid globalGrid>

kind = uniCartGridnumCells = [NX NY NZ]

# All physical values in unitslengths = [LX LY LZ]startPositions = [XBGN YBGN ZBGN]

</Grid>

Note: The variables NX, NY, and NZ, which are defined in the variable definition section of the emPlaneWave.prefile, appear as the x, y, and z values for numCells. Using variables allows you to change the number of cells quicklyand rerun the simulation.

72 Chapter 5. Tutorials

Page 77: VSim In Depth

VSim In Depth, Release 8.2.1

Decomposition Definition

Following the definition of the grid, the input file defines the decomposition. The decomposition determines how thesimulation is broken into domains for parallel processing and which directions are periodic.

The opening tag for the decomposition input block is:

<Decomp decomp>

and the closing tag for the decomposition input block is:

</Decomp>.

Note: Each simulation can use only one decomposition.

############ Define the decomposition###########

<Decomp decomp># Decomposition planes cut entire region# The periodic directionsperiodicDirs = [1 2]

</Decomp>

Electromagnetic Field Definition

Following the definition of the decomposition, the input file defines the plane wave via an EM port macro defined inyee.mac

The yee.mac macro then has to be called again to generate the ampere and faraday updaters necessary to run thesimulation. Altogether the MultiField Block looks like this

############ Define the EM field and describe its boundary conditions###########

addPort(lowerX,LIGHTSPEED,1,1.e10*sin(OMEGA*t)*turnOn(t,TURNONTIME))addPort(upperX,LIGHTSPEED,1,None)#addOpenBoundary(upperX)

saveEmField()

History Definition

Finally, optional History blocks are added to record data from the fields. The E and B fields are recorded at thespecified coordinates for every time step of the simulation.

5.1. Physics Tutorials 73

Page 78: VSim In Depth

VSim In Depth, Release 8.2.1

<History E_y>kind = fieldAtCoordsfield = emField.Eposition = [$XBGN + 0.5*LX$ $YBGN + 0.5*LY$ $ZBGN + 0.5*LZ$]components = [1]

</History>

<History B_z>kind = fieldAtCoordsfield = emField.Bposition = [$XBGN + 0.5*LX$ $YBGN + 0.5*LY$ $ZBGN + 0.5*LZ$]components = [2]

</History>

Now that we have examined the emPlaneWave.pre file’s variables, top-level simulation parameters, grid, decomposi-tion, and electromagnetic field with a boundary condition, we are ready for the next step in the simulation process:running the computational engine Vorpal.

Run VSim to Generate Data

1. To run the file, click on the Run icon in the icon panel on the left side of the window.

2. Click on the Run button in the upper right corner of the Run window as shown in Running the input file

Fig. 5.6: Running the input file

In the directory where you saved the input file, you will find the generated output files.

74 Chapter 5. Tutorials

Page 79: VSim In Depth

VSim In Depth, Release 8.2.1

In VSimComposer, you can also see these output files listed in the Logs and Output Files pane under File Browseras shown in File Browser

Fig. 5.7: File Browser

Visualize the Data

We will use VSimComposer to visualize the emPlaneWave data. VSimComposer can visualize single dump files orentire datasets. Within VSimComposer:

1. Select the Visualize icon in the icon panel on the left side of the VSimComposer window.

2. In the Visualization Controls pane, in the Data Overview data view, expand Scalar Data.

3. Expand E

4. Select E_y.

The right side of the VSimComposer window changes to show the E field at time zero. See VSimComposer windowshowing time zero of emPlaneWave output

Note: The Dump slider at the bottom of the window is set to 0, before the simulation has started.

By moving the slider at the bottom of the VISUALIZATION window you can see the electric field at time steps 0through 100 in increments of 10 time steps.

5. Move the slider to time dump 10 as shown in VSimComposer window showing tenth dump of emPlaneWaveoutput.

5.1. Physics Tutorials 75

Page 80: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 5.8: VSimComposer window showing time zero of emPlaneWave output

76 Chapter 5. Tutorials

Page 81: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 5.9: VSimComposer window showing tenth dump of emPlaneWave output

5.1. Physics Tutorials 77

Page 82: VSim In Depth

VSim In Depth, Release 8.2.1

Now that you are familiar with the simulation process that you will follow for all simulations, you are ready to usethe tutorials. VSim In Depth examines in detail how to create an input file. Each tutorial contains multiple lessons thatdemonstrate how to refine an input file to create different simulations.

5.1.2 Advanced Dipole Above Conducting Plane

The Advanced Dipole Above Conducting Plane example file in the VSimEM package is an ideal file to learn aboutsome of the features provided by the VSimEM package as well as demonstrate some interesting physics.

This section assumes you are familiar with the material in vsim-quick-start and how to access the input file in a runspace, as discussed in Input File Elements.

XSim Block

The XSim Block is the first non-comment lines of code in advancedDipoleAboveConductingPlane.pre. The details ofwhat these do are covered in the Key Parameters. The most important thing to note is the line:

analyzers = [computeFarFieldRadiation.py]

This will load the computeFarFieldRadiation.py script, which is used to post process simulation data to obtain the farfield radiation pattern.

Key Parameters

Next in the input file are the key parameters. Creation of these is detailed in the Key Parameters . For the purposes ofthis tutorial they are irrelevant.

Primary Variables

Next in the input file come the primary variables. These varaiables are determined by numerical data, and theirmodification can alter the simulation significantly. These are also key parameters, and adjustable from the Parameterswindow.

$ NDIM = 3 # Number of dimensions in simulation (1, 2, or 3)

# Primary Variables (Can be modified in XVars)$ ANTENNA_POLARIZATION =2$ HEIGHT = .1$ FREQUENCY = 3.0e9$ PTS_PER_LAMBDA = 10$ LX = 6*HEIGHT$ LY = 6*HEIGHT$ LZ = 6*HEIGHT$ NUM_THETA = 45$ NUM_PHI = 90$ NS = 60$ TIMESTEP_FACTOR = .9$ USEGPU = 0

NDIM is the number of the dimensions in the simulation, for any far field radiation problem this will be 3.

ANTENNA_POLARIZATION will determine which direction our current source will be written in. If it is set to 1it will be Vertical, 2 Horizontal.

78 Chapter 5. Tutorials

Page 83: VSim In Depth

VSim In Depth, Release 8.2.1

HEIGHT sets how far above the ground plane our current source will be located, in terms of meters.

FREQUENCY determines the frequency our current source will operate at.

PTS_PER_LAMBDA is the number of cells in a given wavelength, the higher this value, the more accurate thesimulation. However it will also take longer to run.

LX LY and LZ correspond to the length (in meters) of the simulation domain in the X,Y and Z directions respectively.This value must be large enough to encapsulate the near field of the antenna or else results will be inaccurate.

NUM_THETA Corresponds to the number of points in the theta direction. 60 Is almost always an acceptable choice,lower values will lead to faster simulation times but at the cost of a less accurate result.

NUM_PHI Corresponds to the number of points in the phi direction. 120 Is almost always an acceptable choice, lowervalues will lead to faster simulation times but at the cost of a less accurate result.

Macros of the VSimEM package

VSimEM contains several macros not found in VSimBase. These are antennas, farFields, geometry.

In this example we will make use of farFields, geometry and antennas, in addition to some VSimBase macros as shownbelow

$ import mathphys # General constants$ import geometry # macro for step$ import requiredBlocks # Macro for addRequiredBlocks

$ if USEGPU == 0$ import yee # Macro for saveEmField, addCurrentSource, addOpenBoundary$ import farFields # Macro for addFarFields$ import antennas # Macro for addFarFieldHistory

$ endif

$ if USEGPU == 1$ import yeeGPU # Macro for saveEmField, addCurrentSource, addOpenBoundary$ import farFieldsGPU # Macro for addFarFields$ import antennasGPU # Macro for addFarFieldHistory

$ endif

The antennas and farFields macros are co-dependent and necessary to add far field calculations.

Secondary Variables

This simulation has three secondary variables. These are calculated from the primary variables and are necessary forgrid variables.

$ WAVELENGTH = LIGHTSPEED/FREQUENCY # Wavelength of the EM Wave$ PERIOD = 1./FREQUENCY # Period of the EM WAve$ AMPLITUDE = 8.0e10 # peak amplitude of pulse in volts/meter$ DD = WAVELENGTH/PTS_PER_LAMBDA # Secondary Variable to determine grid \

resolution based on points per wavelength

Grid Variables

These variables determine the size of the grid from the primary and secondary variables.

5.1. Physics Tutorials 79

Page 84: VSim In Depth

VSim In Depth, Release 8.2.1

$ NX = int(LX/DD) # Number of Cells in X$ DX = LX/NX # Length of one cell in the X direction (m)$ XBGN = -0.5*LX # Location (m) in whch the simulation domain begins in the X→˓direction

$ NY = int(LY/DD) # Number of Cells in Y$ DY = LY/NY # Length of one cell in the Y direction (m)$ YBGN = -0.5*LY # Location (m) in whch the simulation domain begins in the Y→˓direction

$ NZ = int(LZ/DD) # Number of Cells in Z$ DZ = LZ/NZ # Length of one cell in the Z direction (m)$ ZBGN = -0.5*LZ # Location (m) in whch the simulation domain begins in the Z→˓direction

For many EM simulations it is more efficent to determine the size and grid resolution from data about the particularsimulation. That way if changes are made the simulation will continue to perform effectively.

For many simulations, and especially far field calculations it is much easier to define the XBGN,YBGN and ZBGNlocations to be negative one half the length of the simulation. That way the exact middle of the simulation is at theorigin, so it is very easy to create symmetric geometries.

Time Variables

Time variables determine the length of a simulation, as well as how often results will be written to memory.

$ DMFRAC = 1. # Set DMFRAC to 1. if no geometry in simulationstandardTimeStep(DMFRAC,TIMESTEP_FACTOR)

$ RISE_TIME = 5.0/FREQUENCY # Amount of time to turn on the current source

$ FLOATTYPE = double # defines precision of floating point numbers, necessary for→˓all simulations$ PROPAGATION_DELAY = (3*HEIGHT)/LIGHTSPEED$ TIME = (1.*LX)/(LIGHTSPEED) +PROPAGATION_DELAY + RISE_TIME # Amount of time to run→˓the simulation (s)$ NSTEPS = int(TIME/DT) # Number of timesteps to run the simulation$ DUMPPERIOD = 50

The macro standardTimeStep will determine the length of a time step according to the Courant-Friedrichs-Levy con-dition. A TIMESTEP_FACTOR is excepted as an argument in order to provide a safety factor off the Courant stabilitylimit

RISE_TIME is a variable to control how long to turn on a current source. By Turning on a current source to slowlyresults will be more accurate.

The TIME variable will set the length of the simulation, which is then translated to a number of time steps in NSTEPS.

The DUMPPERIOD is the number of time steps between memory dumps. While history data is recorded at everytime step on memory dumps all field data is written to an .h5 file.

Required Blocks

createRequiredBlocks is a macro that will establish global variables as well as formally declare the grid and decompo-sition. This can be done by hand, the macro simply saves space. Note that macro calls are NOT preceded by a dollarsign.

80 Chapter 5. Tutorials

Page 85: VSim In Depth

VSim In Depth, Release 8.2.1

createRequiredBlocks(NDIM,FLOATTYPE,DT,NSTEPS,DUMPPERIOD,NX,NY,NZ,LX,LY,LZ,\XBGN,YBGN,ZBGN)

# This macro call sets the grid boundary, Number of timesteps, dump periodicity

Current Source

First a function is defined to describe the behavior and location of a current source.

$ if ANTENNA_POLARIZATION == 2setCurrentSource(Source2,$ANTENNA_POLARIZATION$,

turnOn(t,RISE_TIME)*AMPLITUDE*sin(TWOPI*FREQUENCY*t)*\geoStep(x,-1.25*DX,1.25*DX)*\geoStep(y,-1.25*DY,1.25*DY)*\geoStep(z,HEIGHT-1.*DZ,HEIGHT+1.*DZ)+\turnOn(t,RISE_TIME)*AMPLITUDE*sin(TWOPI*FREQUENCY*t-PI )*\geoStep(x,-1.25*DX,1.25*DX)*\geoStep(y,-1.25*DY,1.25*DY)*\geoStep(z,-HEIGHT-DZ,-HEIGHT+DZ) )

$ elsesetCurrentSource(Source2,$ANTENNA_POLARIZATION$,\

turnOn(t,RISE_TIME)*AMPLITUDE*sin(TWOPI*FREQUENCY*t)*\geoStep(x,-1.25*DX,1.25*DX)*\geoStep(y,-1.25*DY,1.25*DY)*\geoStep(z,HEIGHT-1.*DZ,HEIGHT+1.*DZ)+\turnOn(t,RISE_TIME)*AMPLITUDE*sin(TWOPI*FREQUENCY*t )*\geoStep(x,-1.25*DX,1.25*DX)*\geoStep(y,-1.25*DY,1.25*DY)*\geoStep(z,-HEIGHT-1.*DZ,-HEIGHT+1.*DZ) )

$ endif

Let’s break this function down in order to describe it’s behavior.

turnOn(t/RISE_TIME) This is a function that will cause the current source to ramp up to full amplitude over thelength of the variable RISE_TIME.

AMPLITUDE*sin(TWOPI*FREQUENCY*t) This part of the function determines the user defined amplitude, aswell as the frequency of the sinusoidal source. It would also be here that a phase shift could be taken by addinga factor of pi, e.g. sin(TWOPI*FREQUENCY*t+PI/2)

The lower and upper bounds of the current source are given in the next six arguments.

Boundary Conditions

Since we have already defined our virtual PEC ground plane, all the boundaries will be set to open to allow waves toexit the simulation.

addOpenBoundary(lowerX)addOpenBoundary(lowerY)addOpenBoundary(lowerZ)

addOpenBoundary(upperX)addOpenBoundary(upperY)addOpenBoundary(upperZ)

These macros are also available from the Yee macro, and by defining the position as lowerX/Y/Z and upperX/Y/Z theopen boundary condition is applied to the corresponding face. It is important to note that these are interchangable with

5.1. Physics Tutorials 81

Page 86: VSim In Depth

VSim In Depth, Release 8.2.1

the addConductingBoundary macro. Perfectly Matched Layer (PML) boundary conditions are also available in theYee macro, a description of their operation is given in the yeeMacro section of VSim In Depth.

Add Far Fields

Next the multifield must be configured so that Far Field data can be calculated from the multifield. This is done withthe macro addFarFields, located in it’s parent farFields.

addFarFields()

Save The Multifield

The creation of the simulation is complete when the multifield that we have been generating is saved. This is donewith the saveYeeEmField macro.

saveEmField()

Record The Far Field

VSim records Histories to capture and process data from a simulation run. Many types of histories are available, eachone is detailed in VSim In Depth . For this example we are only interested in the far field data so we use addFarFieldHistory. It is important to note that while most histories are available from the hist macro, this one is packaged withthe antennas macro.

$ RS = LX/2-WAVELENGTH# Determines the radius at which the Near field is measured to take the near \to far field transformation. Generally good practice to make smaller than \the radius of the simulation environment.

addFarFieldHistory(farField,NUM_THETA,NUM_PHI,RS,NS,$RISE_TIME+PROPAGATION_DELAY$,→˓FREQUENCY)#Macro calls history to calculate and record far field data

Far field data is calculated by encapsulating the simulation in a Kirchhoff Sphere, and from the e-fields incident on thesphere the near to far field transformation is made. The radius of the Kirchhoff sphere is determined by the variableRS. It is good practice to make the Kirchhoff sphere as large as possible, but to give a wavelength of guard spacebetwee its edge and the edge of the simulation domain.

The parameters given for addFarField history are specified in VSim In Depth underneath the documentation on theantennas macro.

Further Experiments

The simplest experiment is to watch the change in the number of lobes in the radiation by varying the height andorientation of the dipole.

It is important that the simulation domain be large enough to encapsulate the near field. The most common sign thatthis is not true is a false lobe present in the positive X direction.

82 Chapter 5. Tutorials

Page 87: VSim In Depth

VSim In Depth, Release 8.2.1

5.2 Building Blocks

5.2.1 Boundary Condition Tutorial

The purpose of the boundary condition tutorial is introduce the reader to the various bondary conditions of VSim andshow when to use the which one....

This section assumes you are familiar with the material in vsim-quick-start and how to access the input file in a runspace, as discussed in Input File Elements.

Generic Blocks for all files

We first need to start with a basic setup for all simulations. The code for this is pasted below. To follow along, simplycopy and paste in a text editor for later opening in VSimComposer.

$ import mathphys$ import yee$ import port$ import originRadiatorPort$ import requiredBlocks

# Dey-Mittra fraction$ CFL_FACTOR = 0.9

# Grid Size$ LX = 1.$ LY = 1.$ LZ = 1.$ XBGN = -LX/2.$ YBGN = -LY/2.$ ZBGN = -LZ/2.$ XEND = LX/2.$ YEND = LY/2.$ ZEND = LZ/2.

# Grid Resolution$ NX = 50$ NY = 50$ NZ = 50

# Compute secondary variables$ DX = LX/NX$ DY = LY/NY$ DZ = LZ/NZ

$ NDIM = 3

standardTimeStep(CFL_FACTOR,1.)

# Number of steps - run for N periods$ TIMESTEPS = 100$ DUMPPERIOD = 10

# Dimensionalitydimension = NDIMfloattype = double

5.2. Building Blocks 83

Page 88: VSim In Depth

VSim In Depth, Release 8.2.1

# The grid<Grid globalGrid>numCells = [NX NY NZ]lengths = [LX LY LZ]startPositions = [XBGN YBGN ZBGN]

</Grid>

# Time steppingdt = DTdumpPeriodicity = 10nsteps = 100

# Regular decomposition<Decomp decomp></Decomp>

This code is necessary to establish a simulation domain of 1m^3, centered around the origin with 50 cells in eachdirection. The simulation will run for 100 time steps, dumping the field data every 10.

Open Boundary Conditions

The open boundary condition will set up an open boundary on each face of the simulation domain to which it is applied.This will allow electric and magnetic fields to leave the simulation domain unimpeded. This boundary condition willonly apply to electromagnetic fields, for particles a seperate boundary condition must be written. An example of anopen boundary implemented on all 6 faces of the simulation domain is given below

addOpenBoundary(upperX)addOpenBoundary(upperY)addOpenBoundary(upperZ)addOpenBoundary(lowerX)addOpenBoundary(lowerY)addOpenBoundary(lowerZ)

Conducting Boundary Conditions

A conducting boundary condition is also available to the user. This will reflect all electric fields incident on theboundary condition. Its usage is the same as the OpenBoundary, just a ConductingBoundary is listed in place of theOpenBoundary. This is demonstrated in the code block below

addConductingBoundary(upperX)addConductingBoundary(upperY)addConductingBoundary(upperZ)addConductingBoundary(lowerX)addConductingBoundary(lowerY)addConductingBoundary(lowerZ)

Magnetic Boundary Condition

A magnetic boundary condition will reflect all incident magnetic fields. It works in the exact same manner as the con-ducting boundary condition, with the magnetic field replacing the electric field. The usage of the magnetic boundarycondition is listed below.

84 Chapter 5. Tutorials

Page 89: VSim In Depth

VSim In Depth, Release 8.2.1

addMagneticBoundary(upperX)addMagneticBoundary(upperY)addMagneticBoundary(upperZ)addMagneticBoundary(lowerX)addMagneticBoundary(lowerY)addMagneticBoundary(lowerZ)

Port Boundaries

A tuned phase-velocity port is an open or outgoing boundary condition. Waves traveling at exactly the user spec-ified phase velocity of the boundary will exit the simulation with no reflection at all. Waves traveling at otherphase velocities will partially exit and partially reflect, with a power reflection coefficient of rho=(VphaseWave-VphaseBoundary)^2/(VphaseWave+VphaseBoundary)^2.

This boundary condition is subject to slow-time instability if there is metallic structure and associated fringe or nearfields too close to the boundary. For this reason, the boundary condition works best if used to terminate a length ofsmooth-walled waveguide, or to bound a radiation type simulation, where the boundary is sufficiently distant from theradiation source.

This boundary condition can be called in the same manner as all other boundary conditions, with a phase velocityspecified as well as the face to which it should be applied. This is shown in the code block below.

addPortBoundary(lowerX,VPHASE)addPortBoundary(lowerY,VPHASE)addPortBoundary(lowerZ,VPHASE)addPortBoundary(upperX,VPHASE)addPortBoundary(upperY,VPHASE)addPortBoundary(upperZ,VPHASE)

Origin Radiator Port Boundaries

A tuned phase-velocity port is an open or outgoing boundary condition. Waves traveling at exactly the user spec-ified phase velocity of the boundary will exit the simulation with no reflection at all. Waves traveling at otherphase velocities will partially exit and partially reflect, with a power reflection coefficient of rho=(VphaseWave-VphaseBoundary)^2/(VphaseWave+VphaseBoundary)^2. This particular boundary condition differs from the PortBoundary by being spatially varying. It is designed to allow waves generated from a current source at the origin toleave the simulation space unimpeded.

This boundary condition is subject to slow-time instability if there is metallic structure and associated fringe or nearfields too close to the boundary. For this reason, the boundary condition works best if used to terminate a length ofsmooth-walled waveguide, or to bound a radiation type simulation, where the boundary is sufficiently distant from theradiation source.

This boundary condition can be called in the same manner as all other boundary conditions, with a phase velocityspecified as well as the face to which it should be applied. This is shown in the code block below.

addRadPortBoundary(upperX,VPHASE)addRadPortBoundary(upperY,VPHASE)addRadPortBoundary(upperZ,VPHASE)addRadPortBoundary(lowerX,VPHASE)addRadPortBoundary(lowerY,VPHASE)addRadPortBoundary(lowerZ,VPHASE)

5.2. Building Blocks 85

Page 90: VSim In Depth

VSim In Depth, Release 8.2.1

Matched Absorbing Layer Boundary Condtions

The matched absorbing layer (MAL) was developed by Tech-X scientists as a type of absorbing boundary condition. Itis similar in nature to the more commonly known perfectly matched layer (PML). Unlike the PML however, the MALis isotropic in nature. Will this causes the boundary condition to be less “perfect” it is also more stable in simulationswith particles and slightly more computationally efficent. A MAL boundary condition is physically analagous to aneccosorb free space absorber. A thickness must be specified along with the face that the boundary condition is to beapplied on. This thickness will be applied within the simulation domain. For example if a thickness of 10 grid cellsis specified on the lower X face the layer will between cells 0 and 10. An example of the usage of the MAL is givenbelow.

addMALBoundary(upperX,THICKNESS)addMALBoundary(upperY,THICKNESS)addMALBoundary(upperZ,THICKNESS)addMALBoundary(lowerX,THICKNESS)addMALBoundary(lowerY,THICKNESS)addMALBoundary(lowerZ,THICKNESS)

Perfectly Matched Layer Boundary Conditions

A perfectly matched layer (PML) is a boundary condtion that will absorb incident waves. It is similar to the MALwith the difference of having an ansiotropic damping profile. This is what makes the PML “perfectly matched”. It isnot recommended for use in simulations with particles as the PML can become unstable in particle simulations. Likea MAL a thickness must be specified. It is most effective for the layer to be one to two wavelengths thick. In additionan energy write period, maximum conductivity and conductivity profile exponent must be specified. The energy writeperiod will determine the period at which the energy absorbed by the PML will be written to an output file. Themaximum conductivity determines how conductive the PML will be, typically valued from 3-5*lightspeed/DX. ThePML exponnent is typically between 2 and 10, and determines how quickly the boundary condition ramps up it’sdamping profile.

Unlike the other boudary conditions in VSim a PML must have all faces on which it is to be applied to be specified atthe same time. The usage of the PML macro is given below.

$ SIGMA_MAX = 3*LIGHTSPEED/DX$ PML_EXP = 4$ ENERGY_WRITE_PERIOD = 50addPMLBoundary(lowerX,lowerY,lowerZ,upperX,upperY,upperZ,THICKNESS,\

ENERGY_WRITE_PERIOD,SIGMA_MAX,PML_EXP)

An example applying the PML to only Y and Z faces is given below.

$ SIGMA_MAX = 3*LIGHTSPEED/DX$ PML_EXP = 4$ ENERGY_WRITE_PERIOD = 50addPMLBoundary("",lowerY,lowerZ,"",upperY,upperZ,THICKNESS,\

ENERGY_WRITE_PERIOD,SIGMA_MAX,PML_EXP)

Note that the faces must be specified in the order given.

Perfectly Matched Layer Regions

A perfectly matched layer region is the exact same as a perfectly matched boundary condition, however it can beapplied in absolute grid cells. That is to say instead of specifying faces and a thickness, upper and lower bounds inX,Y and Z can be used. The region in between the upper and lower bound will remain unafffected. This is useful if,for example the PML should only applied to half of one face. An example of this is given below.

86 Chapter 5. Tutorials

Page 91: VSim In Depth

VSim In Depth, Release 8.2.1

$ SIGMA_MAX = 3*LIGHTSPEED/DX$ PML_EXP = 4$ ENERGY_WRITE_PERIOD = 50addPMLRegion(0,0,0,NX,NY/2,NZ,ENERGY_WRITE_PERIOD,SIGMA_MAX,PML_EXP)

5.2.2 Current Source Tutorial

The purpose of the current source tutorial is introduce the reader to the various ways a current source can be added toa simulation.

This section assumes you are familiar with the material in vsim-quick-start and how to access the input file in a runspace, as discussed in Input File Elements.

Generic Blocks for all files

We first need to start with a basic setup for all simulations. The code for this is pasted below. To follow along, simplycopy and paste in a text editor for later opening in VSimComposer.

$ import mathphys$ import yee$ import requiredBlocks

# Dey-Mittra fraction$ CFL_FACTOR = 0.9

# Grid Size$ LX = 1.$ LY = 1.$ LZ = 1.$ XBGN = -LX/2.$ YBGN = -LY/2.$ ZBGN = -LZ/2.$ XEND = LX/2.$ YEND = LY/2.$ ZEND = LZ/2.

# Grid Resolution$ NX = 50$ NY = 50$ NZ = 50

# Compute secondary variables$ DX = LX/NX$ DY = LY/NY$ DZ = LZ/NZ$ TIMESTEP_FACTOR = .9995

$ NDIM = 3

standardTimeStep(CFL_FACTOR,TIMESTEP_FACTOR)

# Number of steps - run for N periods$ TIMESTEPS = 100$ DUMPPERIOD = 10

5.2. Building Blocks 87

Page 92: VSim In Depth

VSim In Depth, Release 8.2.1

# Dimensionalitydimension = NDIMfloattype = double

# The grid<Grid globalGrid>numCells = [NX NY NZ]lengths = [LX LY LZ]startPositions = [XBGN YBGN ZBGN]

</Grid>

# Time steppingdt = DTdumpPeriodicity = 10nsteps = 100

# Regular decomposition<Decomp decomp></Decomp>

addOpenBoundary(upperX)addOpenBoundary(upperY)addOpenBoundary(upperZ)addOpenBoundary(lowerX)addOpenBoundary(lowerY)addOpenBoundary(lowerZ)

This code is necessary to establish a simulation domain of 1m^3, centered around the origin with 50 cells in eachdirection. The simulation will run for 100 time steps, dumping the field data every 10, with open bouindary conditions.

Current Source

A current source is the most basic method of exciting a simulation in VSim. Defining a current source requires a name,polarization, and function describing the location, frequency and amplitude of the current source. The current sourceitself is written to the rhoJ Field. An antenna orientaion of 0 corresponds to the X-axis, 1 to Y-axis and 2 to the Z-axis.This is demonstrated in the code block below.

$ AMPLITUDE = 1000$ FREQUENCY = 1*10e9<function currentSourceProfile>AMPLITUDE*sin(2*PI*FREQUENCY*t)</function>

$ ANTENNA_ORIENTATION = 0$ wlx = -.25 #lower X coordinate$ wly = -.1 #lower Y coordinate$ wlz = -.25 #lower Z coordinate$ wux = .25 #upper X coordinate$ wuy = .1 #upper Y coordinate$ wuz = .25 #upper Z coordinateaddCurrentSource(Source,ANTENNA_ORIENTATION,currentSourceProfile,wlx,wly,wlz,wux,wuy,→˓wuz)

The added current source will perform the following operation on the J field in it’s profile.

𝐹𝑗(𝑥, 𝑦, 𝑧, 𝑡 + ∆𝑡) = 𝐹𝑗(𝑥, 𝑦, 𝑧, 𝑡) + 𝑓(𝑥, 𝑦, 𝑧, 𝑡)

88 Chapter 5. Tutorials

Page 93: VSim In Depth

VSim In Depth, Release 8.2.1

A current source can also be set. This will perform the following operation on the J field in it’s profile. .. math::F_j(x,y,z,t+Delta t) = f(x,y,z,t)

A set current source is applied with the following macro.

setCurrentSource(Source,ANTENNA_ORIENTATION,currentSourceProfile,lx,ly,lz,ux,uy,uz)

Wave Launcher

A wave launcher is a sligtly more complex excitation method. It operates in a similar fashion to a current source, butthe excitation is applied directly to the electric field. It is also unnecesary for the location of the current source to bedefined at the same time as the wave fundction. There are also shortcuts allowing the wave launcher to an entire faceof the simulation, generating a plane wave. The diffrent uses of a wave launcher are shown in the code block below

$ AMPLITUDE = 1000$ FREQUENCY = 1*10e9<function waveLauncherProfile>

AMPLITUDE*sin(2*PI*FREQUENCY*t)</function>$ ANTENNA_ORIENTATION = 0

addWaveLauncher(waveLauncher,ANTENNA_ORIENTATION,waveLauncherProfile,lowerX)addWaveLauncher(waveLauncher,ANTENNA_ORIENTATION,waveLauncherProfile,lowerY)addWaveLauncher(waveLauncher,ANTENNA_ORIENTATION,waveLauncherProfile,lowerZ)addWaveLauncher(waveLauncher,ANTENNA_ORIENTATION,waveLauncherProfile,upperX)addWaveLauncher(waveLauncher,ANTENNA_ORIENTATION,waveLauncherProfile,upperY)addWaveLauncher(waveLauncher,ANTENNA_ORIENTATION,waveLauncherProfile,upperZ)

# If the position parameter is ommitted it can be replaced with user defined# coordinates. This is demonstrated below for a wave launcher to be oriented# in the Y-direction at the center of the simulation domain

$ wlx = -.25 #lower X coordinate$ wly = -.1 #lower Y coordinate$ wlz = -.25 #lower Z coordinate$ wux = .25 #upper X coordinate$ wuy = .1 #upper Y coordinate$ wuz = .25 #upper Z coordinate

addWaveLauncher(waveLauncher,ANTENNA_ORIENTATION,waveLauncherProfile,wlx,wly,wlz,wux,→˓wuy,wuz)

Port Wave Launcher

A port wave launcher is similar to a standard wave launcher, however the wave will only be launched in one direc-tion. This type of wave launcher is very useful as a feeding method for waveguides. However unlike a standardwave launcher no function is necessary to define the launched wave’s frequency or amplitude. A port wave launchermust have a port defined in the same manner as a wave launcher not aligned to a specific boundary. The possibleimplementations of the port wave launcher are given in the code block below.

$ AMPLITUDE = 1000$ FREQUENCY = 1*10e9$ ANTENNA_ORIENTATION = 0$ PHASE_SHIFT = 0# Ant phase shift it must be specified in radians.

5.2. Building Blocks 89

Page 94: VSim In Depth

VSim In Depth, Release 8.2.1

$ wlx = -.25 #lower X coordinate$ wly = -.1 #lower Y coordinate$ wlz = -.25 #lower Z coordinate$ wux = .25 #upper X coordinate$ wuy = .1 #upper Y coordinate$ wuz = .25 #upper Z coordinate

# This will launch a wave in the +X directionlaunchWaveFromPort(portWaveLauncher,ANTENNA_ORIENTATION,FREQUENCY,AMPLITUDE,\

+X,wlx,wly,wlz,wux,wuy,wuz)# This will launch a wave in the -X directionlaunchWaveFromPort(portWaveLauncher,ANTENNA_ORIENTATION,FREQUENCY,AMPLITUDE,\

-X,wlx,wly,wlz,wux,wuy,wuz)# This will launch a wave in the +Y directionlaunchWaveFromPort(portWaveLauncher,ANTENNA_ORIENTATION,FREQUENCY,AMPLITUDE,\

+Y,wlx,wly,wlz,wux,wuy,wuz)# This will launch a wave in the -Y directionlaunchWaveFromPort(portWaveLauncher,ANTENNA_ORIENTATION,FREQUENCY,AMPLITUDE,\

-Y,wlx,wly,wlz,wux,wuy,wuz)# This will launch a wave in the +Z directionlaunchWaveFromPort(portWaveLauncher,ANTENNA_ORIENTATION,FREQUENCY,AMPLITUDE,\

+Z,wlx,wly,wlz,wux,wuy,wuz)# This will launch a wave in the -Z directionlaunchWaveFromPort(portWaveLauncher,ANTENNA_ORIENTATION,FREQUENCY,AMPLITUDE,\

-Z,wlx,wly,wlz,wux,wuy,wuz)

Angled Wave Launcher

An angled wave launcher is like a traditional wave launcher but the wave can be launched at an angle from the portdefined.

angledWaveLauncher(name,FREQUENCY,WAVE_ANGLE_X,WAVE_ANGLE_Y,WAVE_ANGLE_Z,\TRISE,J_ANT,lx,ly,lz,ux,uy,uz)

Circular Wave Launcher

A circular wave launcher is defined in the same manner as Lleft hand polarized or right hand polarized???

angledWaveLauncher(name,FREQUENCY,WAVE_ANGLE_X,WAVE_ANGLE_Y,WAVE_ANGLE_Z,\TRISE,J_ANT,lx,ly,lz,ux,uy,uz)

Turn On

The turnOn function is a handy tool to slowly ramp up any excitation source’s amplitude. This can be useful as if anexcitation source is immediatley turned on at full strength it will not, initially be operating at the intended frequency *.It follows a sine squared profile to turn on the It accepts the variable t (time) and a rise time (in seconds) as arguments.The use of turnOn is given in the code block below.

$ RISE_TIME = 5.0/FREQUENCY$ AMPLITUDE = 1000$ FREQUENCY = 1*10e9<function currentSourceProfile>

turnOn(t,RISE_TIME)*AMPLITUDE*sin(2*PI*FREQUENCY*t)*\

90 Chapter 5. Tutorials

Page 95: VSim In Depth

VSim In Depth, Release 8.2.1

(H(DX-x)*H(x-DX))*(H(DY-y)*H(y-DY))*(H(DZ-z)*H(z-DZ))</function>

5.2.3 Emission Tutorial

The purpose of the emission tutorial is to introduce how to set up and use the emission functionality in the VSimSDpackage. We cover all necessary blocks to set up a emission surface in the simulation, as well as measurements ofvarious physical quantities related to the emission. Macros for photoemission and other functions will also be covered.

This section assumes you are familiar with the material in vsim-quick-start and how to access the input file in a runspace, as discussed in Input File Elements.

Generic Blocks for emission setup

There are three blocks needed to setup an emission structure. The emissionSurface kind of <ParticleSink> defines thegeometrical location of the actual emission surface. <EmissionModel> defines the alogrithm used for the emissionprobability. And switchSpeciesSrc kind of <ParticleSource> defines the emitted species. An example code is pastedbelow.

<ParticleSink dipolePlaneElecLowE>kind = emissionSurfacedirection = [1. 0. 0.]minDim = 1emissionSpecies = vacuumElectronssurface = $SURFACE_LOC + .5*DX$$ MIN_DX_TO_SURFACE = int(($SURFACE_LOC - (XSTART)$)/DX)lowerBounds = [MIN_DX_TO_SURFACE $int(NY/3)$ 0]upperBounds = [$MIN_DX_TO_SURFACE + 1$ NY NZ]emitOrAbsorb = 0<EmissionModel emit>kind = transferMatrixnU = 500xmax = 622.512E-10xmin = 4.62559E-10# Create an STFunc for the electron affinity$ LY_CHI_MIN = YSTART + (LY*0.45)$ LY_CHI_MAX = LY_CHI_MIN + (LY*0.1)<STFunc surfacePotentialFunction>

kind = expressionexpression = (0.55 * H((LY_CHI_MIN) - y)) + (0.55 * H(y - (LY_CHI_MAX))) \

+ (0.17 * (H((LY_CHI_MAX) - y))*(H(y - (LY_CHI_MIN)))) \- 8.77e+6*(x) - 2.52531e-10/(x)

</STFunc></EmissionModel>verbosityEmissionModel = VERBOSITY_EMISSION_SURFACE

</ParticleSink>

<ParticleSource electronsLowESwitchEmitter>kind = switchSpeciesSrcswitchSpecies = vacuumElectronsptclAbsorber = dipolePlaneElecLowEminDim = 1

</ParticleSource>

5.2. Building Blocks 91

Page 96: VSim In Depth

VSim In Depth, Release 8.2.1

This code is necessary to establish emission of vacuumElectrons due to incident primaries. Please refer to the referencemanual for options available for the emission surface and <EmissionModel>.

Macros used in emission

A few macros are used to assist the set up of emisison model.

electronDistribution(photonEnergy, gapEnergy, meanDepth, xSurface).setEmissionSurface(sinkName, sourceName, emittedSpecies, surfaceLocation, \

elecronAffinityInElecronVolt, dielectricConstant, \externalElectricFieldVperM, verbosityLevel)

The electronDistribution macro generates electron distribution according to incident ions. The setEmissionSurfacemacro wrap up all blocks necessary to define an emission strucutre.

5.2.4 Geometry Tutorial

The purpose of the geometry tutorial is to introduce how to use the built in geometry macro to generate shape primi-tives, as well as how to combine them to make more complex structures. In addition the methods used to add an objectfrom a .stl file will be covered.

This section assumes you are familiar with the material in vsim-quick-start and how to access the input file in a runspace, as discussed in Input File Elements.

Generic Blocks for all files

We first need to start with a basic setup for all simulations. The code for this is pasted below. To follow along, simplycopy and paste in a text editor for later opening in VSimComposer.

$ import mathphys$ import geometry

# Dey-Mittra fraction$ CFL_FACTOR = 0.5

# Grid Size$ LX = 1.$ LY = 1.$ LZ = 1.$ XBGN = -LX/2.$ YBGN = -LY/2.$ ZBGN = -LZ/2.$ XEND = LX/2.$ YEND = LY/2.$ ZEND = LZ/2.

# Grid Resolution$ NX = 50$ NY = 50$ NZ = 50

# Compute secondary variables$ DX = LX/NX$ DY = LY/NY$ DZ = LZ/NZ

92 Chapter 5. Tutorials

Page 97: VSim In Depth

VSim In Depth, Release 8.2.1

$ DXI = 1./DX$ DYI = 1./DY$ DZI = 1./DZ

# Courant-Levy-Friedrichs$ DLI = math.sqrt(DXI*DXI + DYI*DYI + DZI*DZI)$ DL = 1./DLI$ DTCFL = DL/LIGHTSPEED$ DT = CFL_FACTOR*0.98*DTCFL

$ NDIM = 3

# Number of steps - run for N periods$ TIMESTEPS = 1$ DUMPPERIOD = 1

# Dimensionalitydimension = NDIMfloattype = double

# The grid<Grid globalGrid>numCells = [NX NY NZ]lengths = [LX LY LZ]startPositions = [XBGN YBGN ZBGN]

</Grid>

# Time steppingdt = DTdumpPeriodicity = 1nsteps = 1

# Regular decomposition<Decomp decomp></Decomp>

This code is necessary to establish a simulation domain of 1m^3, centered around the origin with 50 cells in eachdirection. The simulation will only run for one time step so that the geometry specified will be generated.

Variables of the Geometry Tutorial

Below is a block of code that will supply all variables necessary to demonstrate each of the geometry shape primitives

#Variables for objeccts$ LXO = .3 # specifies length of the object in the X dimension$ LYO = .3 # specifies length of the object in the Y dimension$ LZO = .3 # specifies length of the object in the Z dimension$ RADIUS = .1 # specifies the radius of the object$ INNER_RADIUS = .05 # specifies the inner radius of the object$ A = .2 # Scaling in X (for ellipses)$ B = .2 # Scaling in Y (for ellipses)$ C = .2 # Scaling in Z (for ellipses)$ RND_RADIUS = .03 # specifies radius of a rounded corner

$ xVertex = .3 # Vertex of a paraboloid, in the X direction

$ ya = .2 # 1st point on y axis

5.2. Building Blocks 93

Page 98: VSim In Depth

VSim In Depth, Release 8.2.1

$ yb = -.2 # 2nd point on y axis$ yc = -.2 # 3rd point on y axis$ yd = .2 # 4th point on y axis$ za = .2 # 1st point on z axis$ zb = .2 # 2nd point on z axis$ zc = -.2 # 3rd point on z axis$ zd = -.2 # 4th point on z axis

$ lowerScale = .75$ upperScale = 1

# Lower and upper scale determine the ratio between the radius# of the narrow and wide ends of the cone

$ inner_yVertex = .2 # Vertex of the inner parabola, in the Y direction$ outer_yVertex = .3 # Vertex of the outer parabola, in the Y direction$ inner_halfHeightZ = .1 # Half the width of the inner parabola, in the Z direction$ outer_halfHeightZ = .3 # Half the width of the outer parabola, in the Z direction

$ lengthLowY = .1$ lengthLowZ = .1$ lengthHighY = .3$ lengthHighZ = .3

$ SHAPE_COMPLEMENT = 0$ SHAPE_SCALE = .003$ SHAPE_TRANSLATION = -300000

These variables will be called as necessary when generating geometries.

Basic Concepts of Shape Creation

The geometries created in Vorpal can be thought of similar to working in a machine shop. The simulation domain canbegin as either a void area or an area full of material. This is done with one of the two commands shown below.

resetGeoToVoid()# This will set the simulation domain to be a void area,# which objects can than be added to.

resetGeoToFill(Universe)# This will set the simulation domain to be a filled area, which then can# have sections of material removed by calling shape primitives. Note that# in this case the name of the area must be passed as an argument.

After setting the geometry to be either a full or void region, the various shape primitives or object imports would becalled to define the shape desired. We will get into the specificis of these macro calls later in the tutorial. An exampleversion of each of them is given below.

fillGeoExpression(ObjectName,shapePrimitiveMacro)voidGeoExpression(ObjectName,shapePrimitiveMacro)

fillGeoPython(ObjectName,pythonFunction,shapeComplement)voidGeoPython(ObjectName,pythonFunction,shapeComplement)

fillGeoCad(ObjectName,cadFileName,shapeComplement,scaleCadCoords,translateCadCoords)voidGeoCad(ObjectName,cadFileName,shapeComplement,scaleCadCoords,translateCadCoords)

94 Chapter 5. Tutorials

Page 99: VSim In Depth

VSim In Depth, Release 8.2.1

The geometry then must be saved in order for it to become part of the simulation. This is done with the macro shownbelow.

saveGeoToGridBoundary(Universe,CFL_FACTOR)

Shape Primitive Creation

Each of the shape primitives are listed below as a fill expression. The variables used have been defined by the variabledefinition section. Note that all shape primitives have X as the axial direction. In addition all shapes with a radialpattern are centered around the origin, while those without (e.g. Box) will have their lowest dimension at the origin.In the next section modifying the axial direction as well as moving the shape primitive off the origin will be discussed.By switching the command fillGeoExpression to voidGeoExpression the geometry will be voided.

fillGeoExpression(box ,geoBoxP (x,y,z,LXO,LYO,LZO))fillGeoExpression(roundedBox ,geoRndRectangleSlabXP (x,y,z,LZO,LYO,LZO,RND_→˓RADIUS))fillGeoExpression(torus ,geoTorusX (x,y,z,INNER_RADIUS,→˓RADIUS))fillGeoExpression(EllipticalTorus ,geoEllipticalTorus (x,y,z,A,B,C,RADIUS))fillGeoExpression(sphere ,geoSphere (x,y,z,RADIUS))fillGeoExpression(cylinder ,geoCylinderXP (x,y,z,RADIUS,LXO))fillGeoExpression(roundedCylinder ,geoRndCylinderXP (x,y,z,RADIUS,LXO,RND_→˓RADIUS) )fillGeoExpression(pipe ,geoPipeXP (x,y,z,INNER_RADIUS,→˓RADIUS,LXO))fillGeoExpression(truncatedCone ,geoConeXP (x,y,z,INNER_RADIUS,→˓RADIUS,LXO))fillGeoExpression(ellipTruncatedCone,geoEllipticalConeXP (x,y,z,a,b,A,B,LXO) )fillGeoExpression(truncatedPyramid ,geoTruncatedPyramidXP (x,y,z,lengthLowY,→˓lengthLowZ,\

lengthHighY,lengthHighZ,→˓LXO))fillGeoExpression(Ellipsoid ,geoEllipsoid (x,y,z,A,B,C))fillGeoExpression(Hemisphere ,geoHemiSphereXP (x,y,z,RADIUS))fillGeoExpression(HemiEllipsoid ,geoHemiEllipsoidXP (x,y,z,A,B,C))fillGeoExpression(Paraboloid ,geoParaboloidXP (x,y,z,xVertex,RADIUS))fillGeoExpression(RndCylinder ,geoRndCylinderXP (x,y,z,RADIUS,LXO,RND_→˓RADIUS))fillGeoExpression(TriangleSlab ,geoTriangleSlabXP (x,y,z,LXO,ya,za,yb,zb,yc,→˓zc))# (ya,za)(yb,zb)(yc,zc) are points on the y-z plane specifying the verticies of the→˓trianglefillGeoExpression(QuadrilateralSlab ,geoQuadrilateralSlabXP (x,y,z,LXO,ya,za,yb,zb,yc,→˓zc,yd,zd))# (ya,za)(yb,zb)(yc,zc) (yd,zd) are points on the y-z plane specifying the verticies→˓of the# quadrilateral# Note that for both the triangle and quadrilateral slabs the points must be→˓specified in a# counter clockwise direction relative to standard cartesian co-ordinatesfillGeoExpression(EllipticalCylinder,geoEllipticalCylinderXP(x,y,z,A,B,LXO))fillGeoExpression(EllipticalCone ,geoEllipticalConeXP (x,y,z,A,B,lowerScale,→˓upperScale,LXO))fillGeoExpression(biParabolicSlab ,geoBiParabolicSlabXP (x,y,z,LXO,inner_yVertex,→˓outer_yVertex,\

inner_halfHeightZ,outer_→˓halfHeightZ))

5.2. Building Blocks 95

Page 100: VSim In Depth

VSim In Depth, Release 8.2.1

Shape Primitive Rotation and Translation

By default shape primitives are centered around the origin with X as the axial direction. First we will discuss how tochange the axial direction of a shape primitive.

The first variable declared in the macro call of a shape primitive determines the axial direction. For example if y waslisted first Y would become the axial direction. This is demonstrated in the code block below.

fillGeoExpression(cylinder ,geoCylinderXP(x,y,z,RADIUS,LZ))# Creates a cylinder with x as the axial directionfillGeoExpression(rotated_cylinder,geoCylinderXP(y,x,z,RADIUS,LZ))# Creates a cylinder with y as the axial direction

To translate the location of a shape primitive the value of the translation must be given with the variable specifying thedirection of the translation. In addition adding the value will translate the shape primitive in the negative direction andsubtracting the value will cause the translation to be in the positive direction. This is demonstrated in the code blockbelow.

fillGeoExpression(box,geoBoxP(x+.1,y,z+.1,LXO,LYO,LZO))# This command will translate the box in the negative x and z axis by .1

Combining Shape Primitives to Create a Complex Object

By filling and voiding various shape primitives a more complex shape can be created. This is demonstrated in thecode block below by creating a ridged waveguide. First a box is created, and then by removing sections of it using avoidGeoExpression command the ridge waveguide is defined.

fillGeoExpression(waveguide,geoBoxP(x,y,z,.5,.4,.15))voidGeoExpression(ridge_2,geoBoxP(x-.25,y ,z,.1,.15,.15))voidGeoExpression(ridge_1,geoBoxP(x-.25,y-.25,z,.1,.15,.15))voidGeoExpression(ridge_5,geoBoxP(x ,y-.25,z,.1,.15,.15))voidGeoExpression(ridge_6,geoBoxP(x ,y ,z,.1,.15,.15))

Importing CAD Files

Using fillGeoCad or fillGeoFastCAD, the only type of CAD file available to be imported is an STL file. They can betranslated and scaled in space within the macro call. In addition the shape complement can be added to the simulationif specified. When using the shape complement feature, it is important that the .stl file have a single solid, as is thecommon usage, and that the solid be connected. If there are more than one disconnected shapes, then multiple .stl filesshould be used. An example of how to import a CAD file is given below.

fillGeoCad(objectName,democavity.stl,SHAPE_COMPLEMENT,SHAPE_SCALE,SHAPE_TRANSLATION)voidGeoCad(objectName,democavity.stl,SHAPE_COMPLEMENT,SHAPE_SCALE,SHAPE_TRANSLATION)

By setting SHAPE_COMPLEMENT = 0 the complement of the shape will not be taken. The SHAPE_SCALE canbe used if scaling between units used in the .stl file and Meters, the default units for length in VorpalComposer.The SHAPE_TRANSLATION will translate the .stl file based off the location of the origin and units used in the.stl file. It is important to note that the translation will not be applied in Vorpal units. The translation can be spec-ified as a vector, using the syntax $ SHAPE_TRANSLATION = [TRANSLATION_X_DIRECTION (TRANSLA-TION_Y_DIRECTION) TRANSLATION_Z_DIRECTION]

96 Chapter 5. Tutorials

Page 101: VSim In Depth

VSim In Depth, Release 8.2.1

Importing Python Files

A python defined geometry can also be imported, either as a void or full area as demonstrated below.

fillGeoPython(objectName,pythonFile)voidGeoPython(objectName,pythonFile)

Using the Demo File

A geometry demo file is given as a VSim example. In it all of the code listed above is given, with each section brokenup into macros. At the bottom of the file each of these sections can be demonstrated by calling the respective macro.This code is given below.

### Set Universe as either full or void ####resetGeoToFill(universe)resetGeoToVoid()

###########################################

### Select Section to Demonstrate ###constructGeometry(primitive)#rotationTranslation()#ridgedWaveguide()#cadFile()#pythonFile()

#####################################

### Sets geometry as grid boundary ###saveGeoToGridBoundary(primitive,CFL_FACTOR)

#####################################

5.2. Building Blocks 97

Page 102: VSim In Depth

VSim In Depth, Release 8.2.1

98 Chapter 5. Tutorials

Page 103: VSim In Depth

CHAPTER

SIX

CYLINDRICAL COORDINATES

6.1 Working with Fields in Cylindrical Coordinates

When working in cylindrical coordinates, one must use a special FieldUpdater that is designed specifically for the Co-ordProd grid. In the list of available updaters (found here: fieldupdater), the updaters which work with the CoordProdgrid will be named ending in CoordProd.

If includeCylAxis is set to false in the Grid block, no special care needs to be taken outside of using the properupdater. Boundary conditions will need to be set for both fields and particles (if using) on the lower r boundary sincer=0 is not included in the simulation.

If includeCylAxis is set to true in the Grid block, much consideration needs to go in to properly setting theupdaters (and therefore getting the boundary conditions correct).

Let’s consider the typical case of a standard Yee-Cell implementation for doing the FDTD update on theAmpere and Faraday equations.

When considering the Yee-Cell, the Ez field is the only field located directly at r=0. Therefore, a specialudpate needs to happen at r=0 for Ez. This can be done by using 2 FieldUpdaters. The first will befor the Ampere update for all cells greater than 1 in the r-direction. The second update will be fore theAmpere update at r=0 specifically. In the update specifically for the r=0 location, another parameter,includeCylAxis must also be used.

<FieldMultiUpdater yeeAmpere_z>kind=curlUpdaterCoordProdcomponents=[0]gridBoundary = Anodeinteriorness = cellcenterdifferencing=backward$if INCLUDE_CYL == 1lowerBounds=[0 1 0]$elselowerBounds=[ 0 0 0]$endifupperBounds=[NZ NR NPHI]dtCoefficients=[0.0 1.0]readFieldFactors=[CSQR -EOM1]readFields=[YeeMagField J]writeFields=[YeeElecField]

</FieldMultiUpdater>

$if INCLUDE_CYL == 1<FieldMultiUpdater yeeAmpere_zCyl>

kind=curlUpdaterCoordProdcomponents = [0]

99

Page 104: VSim In Depth

VSim In Depth, Release 8.2.1

gridBoundary = Anodeinteriorness = cellcenterincludeCylAxis=1differencing=backwardlowerBounds=[0 0 0]upperBounds=[NZ 1 NPHI]dtCoefficients=[0.0 1.0]readFieldFactors=[CSQR -EOM1]readFields=[YeeMagField J]writeFields=[YeeElecField]

</FieldMultiUpdater>$endif

6.2 Working with Particles in Cylindrical Coordinates

6.2.1 Density

Care must be taken with 2D ZR cylindrical coordinate systems. The loading algorithm will attempt to load particlesalmost uniformly in both of the dimensions. It does not take into account the larger volume/area represented at largeradius compared with lower radius, so if we allow the particles to uniformly fill this space and allow them to be equallyweighted, we end up with a high density of macro- and physical particles near the axis. We can compensate this by:

Changing the particle loading or emitting profile. For more information on which loading or emittingSTFunc block you should use, please see Controlling the density of physical particles

fixed-weight particles:

If using fixed-weight particles, to load or emit the particles uniformly in the physical space we recommendyou set the density profile to y/LR, where LR is the outer radius of the volume in which you are attemptingto load or emit. y represents the radial coordinate in this coordinate system in VSim.

Due to the effect of the density profile, particle loading or emitting attempts precisely on the axis wouldbe rejected, and the likelihood of a particle load or emit attempt will increase linearly with radius, withthe resultant effect that the density will be uniform in physical space.

variable-weight particles:

If using variable-weight particles, to load or emit the particles uniformly in the physical space we recom-mend you set the particle weight to y/LR, where LR is the outer radius of the volume in which you areattempting to load or emit. y represents the radial coordinate in this coordinate system in VSim. This willresult in particles at higher radius having a larger weight, so representing more physical particles so thatthe density is even.

AND

Secondly, the loading or emitting algorithm will make a cartesian-like assumption about the space inwhich it is loading or emitting particles. The equivalent 2D Cartesian domain would occupy a volumeLR×𝐿𝑍 × 1m, and this will be used to calculate the total number of particle load attempts in 2D (whereLZ is the extent of the load region in the z direction for the cylindrical coordinate system). As our volumeis 𝐿𝑍 × 𝜋 × 𝑅2, we must also correct for this. A cylindrical volume element is 2𝜋 × 𝑟 × 𝑑𝑟 × 𝑑𝑧 and acartesian volume element is 𝑑𝑟 × 𝑑𝑧.

The net effect is that we should use an effective nominal density 2𝜋 × 𝐿𝑅 greater to getthe correct overall number of particles and macroparticles created. Tech-X recommends settinga variable like $ EFFECTIVE_NOMINAL_DENSITY = 2 * PI * LR * NOMDEN and settingnominalDensity=EFFECTIVE_NOMINAL_DENSITY in the input.

100 Chapter 6. Cylindrical Coordinates

Page 105: VSim In Depth

VSim In Depth, Release 8.2.1

Example of randDensSrc in a cylindrical context

# Asssumes PI comes from $import mathphys$ NORMALIZATION = 2.*PI*LR<ParticleSource InitElecDeposition>

kind = randDensSrclowerBounds = [ZSTART 0.]upperBounds = [ZEND LR]density = $NOMDEN*NORMALIZATION$

applyTimes = [DT $101*DT$]

<STFunc macroDensFunc>kind = constantFuncamplitude = y/LR

</STFunc></ParticleSource>

6.2.2 Higher Order Particls in Cylindrical Coordinates

Higher order particles are incompatible with the polar/cylindrical axis. If particles in the simulation pass near thepolar/cylindrical coordinate axis at r=0, only areaWeightingCP or esirk1stOrderCP can be used.

6.2.3 A Note on Charge Depositors

In principle, there is a large degree of freedom in choosing the shape of the particle. Historically, the shape associatedwith simple linear interpolation of the charge to the nearest grid locations has been preferred, since this provides asmall particle foot-print which results in faster execution speed.

Ultimately the shape function for charge and the shape function for current must be consistent with the continuityequation, as done in VSim.

Any of the coordProdGrid (cylindrical coordinate) depositors, such as areaWeightingCP, are coordinate system ag-nostic, and rely on the mesh to specify the elemental areas and volumes. Since these are different for Cartesian andcylindrical coordinates, the algorithm is ultimately different as well. No special measures need to be taken short ofspecifying areaWeightingCP (instead of areaWeighting).

When dealing with cylindrical coordinates, we also realize there is often an extra factor of r to account for. For thedepositors, the extra factor of r occurs naturally in the area and volume elements. No special measures need to betaken.

6.3 Boundary Condition Considerations in Cylindrical Coordinates

If includeCylAxis is set to false in the Grid block, boundary conditions will need to be set for both fields andparticles (if using) on the lower r boundary since r=0 is not included in the simulation.

If includeCylAxis is set to true in the Grid block, boundary conditions will NOT need to be set for both fieldsand particles (if using) on the lower r boundary since r=0 is included in the simulation. This is done automatically byvorpal.

Note: The absorbingBoxCylAxis macro will properly exclude the cylindrical axis when creating particle boundaryconditions. Use this macro (if desired) when includeCylAxis is true.

6.3. Boundary Condition Considerations in Cylindrical Coordinates 101

Page 106: VSim In Depth

VSim In Depth, Release 8.2.1

Note: Special care does need to be taken when implementing the FieldUpdaters to properly account for the lower rboundary. See: Working with Fields in Cylindrical Coordinates for more information.

102 Chapter 6. Cylindrical Coordinates

Page 107: VSim In Depth

CHAPTER

SEVEN

GEOMETRIES

7.1 Importing Geometries in VSim (STL, STEP, POLY, VTK)

Supported file types include:

• Step Files (.stp, .step, .p12)

• STereoLithography Files (.stl)

• Visualization Toolkit Files (.vtk)

• Polygon File Format (.ply)

The Vorpal engine itself can only handle files of the STereoLithography (stl) type. However, if you have any of theother supported file types, you can import them in VSimComposer using the visual setup. Any geometries in the visualsetup that have materials defined, are converted to stl files. The Vorpal engine can then import and read those stl filesin the simulation.

If you are using the visual setup of VSimComposer to do your simulations, nothing special needs to be done.

If you are using text-based setup files, you can use the visual setup of VSimComposer to first generate your stl filefrom the other supported types, and then import that stl file in your text-based file.

To learn more about text-based stl file importing, please see gridrgnbndry.

Note: If you have other types of geometry files such as IGES, SAT or DXF, you may import them into a CAD tool(ProE, Solidworks, CATIA) and re-export as an STL for use in VSim.

103

Page 108: VSim In Depth

VSim In Depth, Release 8.2.1

104 Chapter 7. Geometries

Page 109: VSim In Depth

CHAPTER

EIGHT

MACROS

8.1 Macros Overview

8.1.1 Overview of Macros

The great flexibility of the VSim input file languages allows VSim to be used to model a wide variety of systems, butat the same time can make daunting the construction of the input files. Macros simplify input file construction throughproviding a mechanism for encapsulating commonly used input file snippets. A user can then put into the input fileonly the macro, and then it will be expanded into the full input file at the time of pre-processing the prefile.

8.1.2 Basics of Macro Definition and Usage

A macro file contains one or more macros. A macro is invoked as a parameterized token with the result being that thebody of the macro is place into the input file. In this section we dicuss the basics of macros, including their definitionand use.

Macros in Brief

In its simplest form, a macro provides a way to substitute a code snippet from an input file:

<macro snippet>line1line2line3

</macro>

In this example, every occurrence of the code named snippet in the input file will now be replaced by the three linesdefined between the <macro> and </macro> tags.

For example, you could define a macro to set up a laser pulse like this:

<macro myLaser>EmField<BoundaryCondition LaserPulseBC>... some regular boundary conditions ...</BoundaryCondition>

</macro>

You could then call your myLaser macro within the input file like this:

105

Page 110: VSim In Depth

VSim In Depth, Release 8.2.1

<Field exampleField>kind = myLaser

</Field>

The VSim engine (Vorpal) will expand the input file use of your macro into:

<Field exampleField>kind = EmField<BoundaryCondition LaserPulseBC>

... some regular boundary conditions ...</BoundaryCondition>

</Field>

Macro Parameters

Macros can take parameters, allowing variables to be passed into and used by the macro. Parameters are listed inparentheses after the macro name in the macro declaration, as in this example:

<macro box(lx, ly, lz, ux, uy, uz)>lowerBounds = [lx ly lz]upperBounds = [ux uy uz]

</macro>

Once a macro is defined, it can be used by calling it and providing values or symbols for the parameters. The macrowill substitute the parameter values into the body provided. Calling the example above with parameters defined likethis:

$ NX = 10$ NY = 20$ NZ = 30box(0, 0, 0, NX, NY/2, NZ)

will create the following code fragment in the processed input file:

lowerBounds = [0 0 0]upperBounds = [10 10 30]

Note: The parameter substitution happened in the scope of the caller. Parameters do not have scope outside of themacro in which they are defined.

Macro Overloading

As with symbols, macros can be overloaded within a scope. The particular instance of a macro that is used is deter-mined by the number of parameters provided at the time of instantiation. This enables the user to write macros withdifferent levels of parameterization:

<macro circle(x0, y0, r)>r**2 - ((x-x0)**2 + (y-y0)**2)

</macro><macro circle(r)>

circle(0, 0, r)</macro>

106 Chapter 8. Macros

Page 111: VSim In Depth

VSim In Depth, Release 8.2.1

Looking in the example above, whenever the macro circle is used with a single parameter, it creates a circle aroundthe origin; if you use the macro with 3 parameters, you can specify the center of the circle.

The macro substitution does not occur until the macro instantiation is actually made. This means that you do not haveto define the 3-parameter circle prior to defining the 1-parameter circle, even though the 1-parameter circle refers tothe 3-parameter circle. It is only necessary that the first time the 1-parameter circle is instantiated, that 3-parametercircle has already been defined, otherwise you will receive an error.

Defining Functions Using Macros

Macros can be particularly useful for defining complex mathematical expressions, such as defining functions inSTFunc blocks with kind = expression.

Consider a macro that should simplify the setup of a Gaussian. One could define the following macro:

<macro badGauss(A, x, sigma)>A * exp(-x**2/sigma)

</macro>

While this is a legitimate macro, an instantiation of the macro via:

badGauss(A0+5, x-3, 2*sigma)

will result in:

A0+5*exp(-x+3**3/2*sigma)

which is probably not the expected result. One alternative is to put parentheses around the parameters whenever theyare used in the macro.

<macro betterGauss(A, x, sigma)>((A) * exp(-(x)**2/(sigma)))

</macro>

This will ensure that the expressions in parameters will not cause any unexpected side effects. The downside of thisapproach, however, is that the macro text is hard to read due to all the parentheses. To overcome this issue, VSimprovides a mechanism to automatically introduce the parentheses around arguments by using a function block

<function goodGauss(A, x, sigma)>A * exp(-x**2/sigma)

</function>

The previous example will produce the same output as the betterGauss macro, but without requiring the additionalparentheses in the macro text.

More About Parameters

In the previous examples, parameters were always single tokens or simple expressions. However, the preprocessorallows you to pass parameters that span multiple lines. This can be particularly useful for writing larger macros. Anexample of multiple line parameter passing would be defining a general particle source. This example below shows amacro defining a general species:

<macro ions(name,charge,extra)><Species name>kind = relBorisemField = emSum

8.1. Macros Overview 107

Page 112: VSim In Depth

VSim In Depth, Release 8.2.1

charge = charge extra<ParticleSink leftAbsorber>

kind = absorberlowerBounds = [-1 -1 -1]upperBounds = [ 0 NY1 NZ1]

</ParticleSink></Species>

</macro>

The parameter extra can be an arbitrary string such as:

ions(species1, 1.6e-19, "mass = 1e-28")

or it can be an empty string, if no additional information is needed:

ions(species2, 1.6e-19, "")

In addition, you can add entire input file blocks to this parameter. Assume we have a macro called loader, defined asfollows:

<macro loader(ionDens)><ParticleSource ptcl_loader>

kind = randDensSrclowerBounds = [ -0.05 -0.05 -0.2]upperBounds = [ 0.05 0.05 0.2]density = ionDensvbar = [0. 0. 0.]vsig = [V_ion_rms V_ion_rms V_ion_rms ]<STFunc macroDensFunc>

kind = expressionexpression = H(0.1 - sqrt(x*x + y*y))

</STFunc></ParticleSource>

</macro>

Using this macro with the ions macro defined previously, we can now create an ion species with a source via a singleline:

ions(species3, 1.6e-19, loader(1e18))

Importing Macros from Files

It is also possible to import a macro file that contains your own custom macros. This is useful when reusing one morecustom macros over multiple simulations. For example, physical constant definitions or commonly-used geometrysetups can be stored in files that can then be reused. The macro file must have a .mac extension on it to be importedas a local macro, and it must be in either the directory of of your .pre file, or its directory must be in the environmentvariable, TXPP_PATH.

To extend the example above, say the macro myLaser is in the file Lasers.mac, the input file would look like this:

$ import Lasers.mac

<Field exampleField>kind = myLaser

</Field>

108 Chapter 8. Macros

Page 113: VSim In Depth

VSim In Depth, Release 8.2.1

Vorpal will expand the input file use of your macro into:

<Field exampleField>kind = EmField<BoundaryCondition LaserPulseBC>

... some regular boundary conditions ...</BoundaryCondition>

</Field>

The macro definition would remain the exact same. As long as the macro file is imported properly, it is just like havingit defined explicitly in the input file.

Files are imported via the import keyword:

$ import FILENAME

where FILENAME represents the name of the file to be included. VSim applies the standard rules for token substitutionto any tokens after the import token. Quotes around the filename are optional and computed filenames are possible.

Conditionals

The Vorpal preprocessor includes both flow control and conditional statements, similar to other scripting languages.These features allow the user a great deal of flexibility when creating input files.

The most general form for a conditional is

$ if (COND1)...

$ elseif (COND2)...

$ elseif (COND3)...

$ else...

$ endif

where there is a stanza starting with $ if, zero or more stanzas beginning with $ elseif, and zero or one stanzabeginning with $ else. As in general usage, when a stanza is reached where the conditional evaluates to True,those lines are pre-processed and the resulting lines are inserted into the input file. If a conditional statement doesnot evaluate to True, then that branch of the conditional statement is skipped by the pre-processor. If no branchesevaluate to True, then the lines after the else (if present) are processed. Conditionals can be arbitrarily nested. Useof parenteses around testing condition expressions is important if when also using the boolean operators not, and, oror.

Most valid python expressions can be inserted for the conditional test, but this is an area continuously undergoingimprovement, so there may be some volatility. In particular, it is desired to have a conditional test that evalutesin Python to either True or False. As an example, a variable that is undefined both $ if (undefvar) and $ ifnot (undefvar) branches will be skipped by the pre-processor because neither evaluates to True. For the moment,other unexpected behavior can occur when checking for empty strings. The only valid way to do this for now is to use$ if (isEqualString(s1, "")). The isEqualString should generally be used for strings to be careful, butmost string comparisons, except for those involving empty strings, work in the manner expected for Python evaluation.Support for empty string comparisons using standard Python syntax will be supported in the future.

8.1. Macros Overview 109

Page 114: VSim In Depth

VSim In Depth, Release 8.2.1

Example Conditional Statements

$ if (NDIM == 2)$ dt = 1/(c * sqrt(1/dx**2+1/dy**2))$ else$ dt = 1/(c * sqrt(1/dx**2 + 1/dy**2 + 1/dz**2))$ endif

A conditional statement can also use Boolean operators:

$ A = 0$ B = 0$ C = 1## Below, D1 is 1 if A, B, or C are non-zero. Otherwise D1=0:$ D1 = (A) or (B) or (C)## Below, D2 is 1 if A is non-zero or if both B and C are non-zero.# Otherwise D2=0:$ D2 = (A) or ( (B) and (C) )## This can be also be written as an if statement:$ if (A) or ( (B) and (C) )$ D3 = 1$ else $$ D3 = 0$ endif

Repetition

For repeated execution, Vorpal provides while loops; these take the form:

$ while (COND)...

$ endwhile

which repeatedly inserts the loop body into the output. For example, to create 10 stacked circles using the circle macrofrom above, you could use:

$ n = 10$ while (n > 0) circle(n)$ n = n - 1$ endwhile

Recursion

Macros can be called recursively. E.g. the following computes the Fibonacci numbers:

<macro fib(a)>$ if (a < 2)

a$ else

110 Chapter 8. Macros

Page 115: VSim In Depth

VSim In Depth, Release 8.2.1

fib(a-1)+fib(a-2)$ endif

</macro>fib(7)

Note: There is nothing preventing you from creating infinitely recursive macros; if terminal conditions are not givenfor the recursion, infinite loops can occur.

Requires

When writing reusable macros, best practices compel macro authors to help ensure that the user can be prevented frommaking obvious mistakes. One such mechanism is the requires directive, which terminates translation if one or moresymbols are not defined at the time. This allows users to write macros that depend on symbols that are not passed asparameters. For example, the following code snippet will not be processed if the symbol NDIM has not been previouslydefined:

<macro circle(r)>$ requires NDIM$ if (NDIM == 2) r**2 - x**2 - y**2$ endif$ if (NDIM == 3) r**2 - x**2 - y**2 - z**2$ endif

</macro>

String Concatenation

One task that is encountered often during the simulation process is naming groups of similar blocks, e.g. similarspecies. Macros can allow us to concatenate strings to make this process more clean and simple. However, based onthe white-spacing rules, strings may be concatenated with a space between them. For example,

$ a = hello$ b = worlda bwill result inhello world

The space insertion is not done, however, if the last character of the first string is not a letter or a number, or if the firstcharacter of the second string is not a letter. We can avoid this rule altogether by using the concatenate macro:

concatenate(hello, world)

in which case, the result will always be:

helloworld

The concatenate macro is located in the file listUtilities.mac, and is always available at the top level for importa-tion.

8.1. Macros Overview 111

Page 116: VSim In Depth

VSim In Depth, Release 8.2.1

8.1.3 Version 8 New Macro Infrastructure

As of version 8, a new set of macros in a streamlined organization following a well defined methodology is provided.The philosophical change is that rather than having only macros that write out input file snippets directly, now thereare macros that instead write the snippets into “accumulation variables”. Then, at the end of the file, a call is madeto finalize(), which writes out the accumulated information with the nesting needed for correct interpretation byVorpal. A requirement for use of these version 8 macros is that the input (.pre) file must adhere to some structure,but the result is a much less constrained structure compared with the previous macros, which had to be placed in thepre-file in the location where the substitution was desired.

Here we provide an overview of these new macros. In the following we will define direct macros to be those thatdirectly write snippets. They can be used just as macros were used before. We define accumulation macros to be thosethat add snippets to accumulation variables. The latter are often effected by the former, as we shall see. The intentionis to deprecate the old macros in version 9 and remove them in version 10.

Version 8 Macros Overview: Namespacing and input file structure

All global variables, e.g., the accumulation variables (to be discussed later), for the new macros start with VPM_. Thestandard macros are not namespaced, but may be namespaced in a future release. Also, there are variables that arenamespaced starting with TXU_; for instance variables that describe units.

With the new macros, the input file has to have a particular structure:

• Preamble: Setting of user-defined variables and variables that determine the type of simulation, e.g., electro-magnetic versus electrostatic.

• Macro file importing.

• The user-defined regular and space-time functions.

• The ordered macros, i.e., grid and timing.

• The unordered macros (for all other dynamics).

• Finalization.

The Preamble

The Preamble consists of the setting of the variables that one might want to use in the input file. For pre files generatedfrom visual setup, the input file preamble begins with

######################################################### This PRE file,# emcartfull.pre,# was generated from the simulation definition file,# emcartfull.sdf,# by the sdf2vpre translator.# Any changes to this file will be lost if the# translator is rerun.########################################################

######################################################### Ordered blocks########################################################

112 Chapter 8. Macros

Page 117: VSim In Depth

VSim In Depth, Release 8.2.1

######################################################## User defined constants and parameters#######################################################

$ import mathphys

$ WAVELENGTH = 1.00000000000000e-01$ WIDTH = 3*WAVELENGTH$ DX = WAVELENGTH/16$ QWID = 0.5*HALFWIDTH$ EXPFAC = 0.5/(QWID^2)$ XeMass = 131.3*PROTMASS

Of course, the comments (anything after the #) are not processed, nor are the blank lines. The user has freedom tochoose the variable names provided they do not clash with the names in mathphys.mac, nor do they begin with VPM_or TXU_, which are preserved for distinguishing variables that are defined for system use. The macro system definesvarious boolean variables, so the user should not define variables with names like True or FALSE. Similarly, commonmath functions and Python system functions are reserved and should not be used as variable names. For this reason,users should not assign variable names like cos, sqrt, open, or float.

Next follows the basic variables that define the simulation:

######################################################## Simulation definition from the basic settings#######################################################

$ VPM_COORDINATE_SYSTEM = "cartesian"# cylindrical not found.$ VPM_NDIM = "3"$ VPM_PRECISION = "double"$ VPM_USE_GPU = "False"$ VPM_SIMULATION_TYPE = "electromagnetic"# electrostatic not found.$ VPM_GRID_SPACING = "uniform"$ VPM_INCLUDE_PARTICLES = "False"# include particles.estimated max electron density not found.# include particles.estimated min electron temperature (eV) not found.$ VPM_TOP_LEVEL_VERBOSITY = VPM_INFO$ VPM_GRID_TYPE = UniformCartesian

and if VPM_INCLUDE_PARTICLES is True, one must also define

$ VPM_MAX_ELECTRON_DENSITY = "1.e18"$ VPM_MAX_ELECTRON_TEMP_EV = "1.0"

These variables are used later to calculate the time step, if one is not provided, by later macros.

Macro Importing

To obtain that standard macros, the user need import only a single file, VSim,

$ import VSim

This in turn imports all of the standard macro files needed for the simulation of type defined in the Preamble. Thisalso initializes all of the accumulation variables, which will be further discussed below. If a user creates custom macro

8.1. Macros Overview 113

Page 118: VSim In Depth

VSim In Depth, Release 8.2.1

files, they should be imported after the above statement. E.g.,

$ import mymacrofile

User-defined regular and space-time functions.

The user defines regular and space-time functions in this part of the file in the regular way. Examples are shown below.

######################################################## User defined functions#######################################################

<function SomeFunc(x,y)>cos(x)*sin(y)

</function>

######################################################## User defined space-time functions#######################################################

$ Jz = exp(-EXPFAC*(y^2+z^2))*sin(OMEGA*t)

The Ordered Macro Calls

There are only two ordered macro calls. Each must be preceded by the definition of some global variables. The gridmacro call comes first and has the form,

######################################################## Translation of grid#######################################################

$ VPM_BGN0 = 0 * TXU_METERS$ VPM_BGN1 = NEGHW * TXU_METERS$ VPM_BGN2 = NEGHW * TXU_METERS

$ VPM_L0 = $LENGTH - 0$ * TXU_METERS$ VPM_L1 = $HALFWIDTH - NEGHW$ * TXU_METERS$ VPM_L2 = $HALFWIDTH - NEGHW$ * TXU_METERS

$ VPM_N0 = NX$ VPM_N1 = NPERP$ VPM_N2 = NPERP

$ VPM_PERIODIC_DIRS = []

setGridData(VPM_NDIM, VPM_GRID_TYPE)

with the following definitions

VPM_BGN0: The start of the grid in the first coordinate.

VPM_BGN1: The start of the grid in the second coordinate.

VPM_BGN2: The start of the grid in the third coordinate.

VPM_L0: The extent of the grid in the first coordinate.

114 Chapter 8. Macros

Page 119: VSim In Depth

VSim In Depth, Release 8.2.1

VPM_L1: The extent of the grid in the second coordinate.

VPM_L2: The extent of the grid in the third coordinate.

VPM_N0: The number of cells in the first direction.

VPM_N1: The number of cells in the second direction.

VPM_N2: The number of cells in the third direction.

VPM_PERIODIC_DIRS: An array listing the coordinate directions in which one has periodic boundary conditions.

Following that is the timing setup, which has the form,

######################################################## Translation of the time group#######################################################

$ VPM_DT = "0.0"$ VPM_CFL_NUMBER = "0.95"$ VPM_NSTEPS = 100$ VPM_DUMP_PERIOD = 20

setTimingData()

VPM_DT: The time step for the simulation. If it is set to zero, the setTimtingData macro will provide a best guess.

VPM_CFL_NUMBER: This is used when VPM_DT is set to zero. The time step is set to this factor times the maximumknown stable time step.

VPM_NSTEPS: The number of time steps for the simulation.

VPM_DUMP_PERIOD: The number of time steps between each data dump.

The Unordered Macro Calls

With the new version-8 macros, one can now call the accumulation macros in any order. For example, one can addboundary conditions via

addBoundaryLauncher(boundaryLauncher0, ElectricField, 0.0, None, 0.0, upperY)addMalBoundary(mal0, emField, lowerY, MALWID)addOpenBoundary(open0, emField, upperX)

and one can add particle species, sinks and loaders with

addParticleSpecies(Xenon, 1.602176487e-19, XeMass, relBoris, variableWeights, 1.e18,→˓5.0, None)

addParticleSpeciesSink(absorbAndSave0, electrons0, absAndSav, lowerX)addParticleSpeciesLoader(particleLoader0, xvLoaderEmitter, electrons0, 0.→˓00000000000000e+00, 0.00000000000000e+00, relativeDensity, 1.0, grid,→˓beamVelocityGen, [0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00],→˓[5.00000000000000e+06, 5.00000000000000e+06, 5.00000000000000e+06], [-0.5, -0.5, -0.→˓5], [0.5, 0.5, 0.5])addParticleSpecies(electrons0, ELECCHARGE, ELECMASS, relBoris, variableWeights, 1.e18,→˓ 5.0, None)

From the above one can see that the order is independent, as the species, electrons0, is added after its loaders andsinks. However, if a loader or sink is added for a species that ultimately is not added, no such species shows up in thesimulation.

8.1. Macros Overview 115

Page 120: VSim In Depth

VSim In Depth, Release 8.2.1

Finalization

Finalization consists of a single line,

$ finalize()

This macro takes all of the accumulated descriptions of the simulation, held in the accumulation variables, and writesit into the file with correct ordering and nesting.

Version 8 Macros Methodology

The basic units of the new macro system are the direct macros. An example of one from solvers.mac is

# Add the base solver block to an accumulation variable.# @param name the accumulation variable# @param krySize the Krylov subspace size (for gmres)# @param orthogType the orthogonality type for the Krylov subspace (for gmres<macro writeBaseSolverBlock(name, krySize, orthogType)>

<BaseSolver myBS>kind = name$ if isEqualString(name, generalized minimal residual solver)

kspace = krySizeorthog = orthogType

$ endif</BaseSolver>

</macro>

Like all macros, this macro has basic documentation in the macros file giving the macro name along with any param-eters. In this case the macro directly writes an input file fragment, hence its name. Direct macros can be used just likeany of the traditional macros, where the user controls the file structure, and the user knows where to place this macrocall for the desired effect. Because all direct macros directly write, their names begin with write.

The above is actually an independent direct macro in that it can be used at any place in the file (though it may not makesense in any place). In particular, it need not be preceded with any other macros that set any accumulation variables,which we now turn to.

However, for deferred writing to allow the system to get the order of the macros correct, instead of writing directly,we accumulate these blocks in accumulation variables using accumulation macros, and then we write those out atfinalization time. An example of an accumulation macro is

# Add the base solver block to the accumulation variable, VPM_MATRIX_SOLVER.# Used for iterative solvers, such as gmres.# @param name the name of the base solver block# @param krySize the Krylov subspace size (for gmres)# @param orthog the orthogonality type for the Krylov subspace (for gmres)<macro addBaseSolver(name, krySize, orthog)>

$ requires VPM_MATRIX_SOLVER$ VPM_MATRIX_SOLVER = appendToBlock(VPM_MATRIX_SOLVER, writeBaseSolverBlock(name,

→˓krySize, orthog) )$ global VPM_MATRIX_SOLVER

</macro>

This macro counts on there being a global accumulation variable, VPM_MATRIX_SOLVER, which is defined insolvers.mac. It is important to initialize accumulation variables to an empty string prior to accumulating input filelines into them. Thus, definition of an accumulation variable should be of the form,

116 Chapter 8. Macros

Page 121: VSim In Depth

VSim In Depth, Release 8.2.1

$ VPM_MATRIX_SOLVER = ""

Accumulation into a variable appends to that variable the output of the previous macro, e.g.writeBaseSolverBlock(...). With this device, we now have the base solver stored in the variableVPM_MATRIX_SOLVER, and we can write that variable out where it is needed.

For example, to write out a linear solver, one call the dependent direct macro,

# Write the interative poisson solver block. When used, it must come# after addBaseSolver and addPreconditioner, as it writes the accumulation# variables for the base solver and the preconditioner.# @param maxIt the maximum number of iterations allowed.# @param tol the tolerance for the solution# @param met the metric for convergence, e.g., L1, L2# Verbosity set to same as top level verbosity<macro writePoissonSolverIterativeBlock(maxIt, tol, met)>

$ requires VPM_TOP_LEVEL_VERBOSITY<LinearSolver linearSolver>kind = iterativeSolververbosity = VPM_TOP_LEVEL_VERBOSITYmaxIterations = maxIttolerance = tolmetric = metVPM_MATRIX_SOLVERVPM_PRE_CONDITIONER

</LinearSolver></macro>

This is called dependent because it relies on previous macro calls to have defined VPM_MATRIX_SOLVER andVPM_PRE_CONDITIONER. This writes (and so is a direct macro) a linear solver block, which can be used insidea multifield block. A user may use this macro just like any of the pre-version-8 macros, provided that the variables,VPM_MATRIX_SOLVER and VPM_PRE_CONDITIONER have been appropriately initialized.

In the application to multifields, one has at least the updaters, the update steps, and the update step order. The abovemacro would be used to write an update step. It is accumulated in the variable, VPM_ES_SOLVER_UPDATERS,which is finally written into the multifield block during the call to finalize().

Version 8 Macro Files Organization

There are three sections in a macro file for (1) Public macros, (2) global (including accumulation) variables, and (3)Private macros. When working in the visual setup, the problem description is written out in an xml-like format thatthe translator translates to macro calls, that are then processed to produce input file lines. Because most users onlyever see these macro calls, they come first in the macro file. After those macro calls, the file defines the accumulationvariables and then the other macros.

Public Macros

These are the macros currently written by the translator plus a few more, so they are sometimes called translatormacros. They can be order dependent. For example, the macros calls for defining an iterative solver must occur as

addBaseSolver(bicgstab)addPreconditioner(multigrid, SA, 30, GaussSeidel, 3, before, Jacobi, 1.→˓33300000000000e+00, 0.00000000000000e+00, increasing)# This writes preconditioner, so it must be last.addPoissonSolver(relPerm, 1000, 1.00000000000000e-08, r0)

8.1. Macros Overview 117

Page 122: VSim In Depth

VSim In Depth, Release 8.2.1

Global (including accumulation) Variables

These are the variables into which one accumulates blocks for later printing in the correct order. All variables arenamespaced with VPMT_, VPM_ or TXU_ so that the user can confidently use names that are not namespaced withVPMT_, VPM_, or TXU_ provided they also avoid the names in mathphys.mac.

There is no guarantee that these variables will not change with future versions.

Private Macros

The translator macros make use of many other macros to accumulate blocks. These other macros take many forms:direct macros, utility macros, string manipulation, and so forth. These macros are not guaranteed to be stable betweenversions unless they appear in the documentation.

Top Level Macro Files

The top-level macro files are VSim.mac, VSimEm.mac, and VSimEs.mac. These control which other macro filesare included, provide some universally used macros, and define the basic accumulation variables. In particular, ifVPM_SIMULATION_TYPE equals Electromagnetic, then VSimEm.mac is loaded and it loads the macro files neededfor electromagnetic simulations. If VPM_SIMULATION_TYPE equals Electrostatic, then VSimEs.mac is loadedand it loads the macro files needed for electrostatic simulations. Subsequently, VSim.mac loads the macro files forparticles, fluids, collisions, etc., depending on what the preamble requested.

Remaining Macro Files

The remaining macro files are organized by functionality. For example, electrostatic boundary condition macros arein esbcs.mac. The particle macros are in particles.mac. When following the standard organization decribed above, theaccumulation variables for any macros in a macro file are defined and initialized in either that file or in a previouslyloaded file.

Selective Processing

txpp.py processes macros by substitution, giving numerical values to parameters and creating input file blocks that canbe read by Vorpal. txpp.py can also perform selective processing using the ‘‘–selective” flag to process a subset of themacros. At present, this has been tested on files that were generated from visual setup.

Running txpp.py with the selective option, e.g.

txpp.py --selective=fn input.pre -o input.ppp

expands the macros listed in the file named, fn. With

txpp.py --selective="" input.pre -o input.ppp

the file, expandmacros.txt, will be sought. It finds the file by following the usual import path, which includes themacros directory in which there is expandmacros.txt containing

$ cat expandmacros.txt# Below are the write macros that must be expandedwriteGridwriteMultiFieldwriteEsFieldUpdaterBlockwriteParticleSpeciesBlock

118 Chapter 8. Macros

Page 123: VSim In Depth

VSim In Depth, Release 8.2.1

writeImpactColliderBlockwriteParticleAbsorberEmitterHistoryBlock# Below or the variables that must be expandedVPMT_NDIM # Expanded for clean limitsVPMT_INCLUDE_PARTICLES # Remove condition blocks depending on this# Add more expansions here

To have more macros or variables expanded, copy this file next to your input file, and edit it to add all the macros youwant expanded, one per line.

By this method you should be able to arbitrarily morph an sdf-generated pre file to any .ppp file that is between thesdf-written pre file and the final .in file. One can then run vorpal using the ppp file as input, or one can further or fullyprocess the ppp file.

Writing Your Own Macros

Suggest that one starts with the Composer, creates a pre file, then partially processes, then uses macros in previousversions.

8.1.4 Macro Availability by Package

VSim contains a number of pre-defined macros that are used throughout the example input files available through theVSimComposer interface. You may find the VSim macros to be helpful in your own simulations.

Some macros are encrypted and will decrypt with you run Vorpal only if you have the proper VSim license.These macros are listed in the table below, which shows which license they require. Unlisted macros areavailable in all packages, but the Vorpal capabilities they invoke may be available in only certain packages.

Macro File Package AvailibilityDrudeDebyeLorentzDielectric VSimEMantennas VSimEMantennasGPU VSimEMdeymittra VSimEM VSimMD VSimPDdielectric VSimEMdielectricGPU VSimEMesGridBoundary VSimEM VSimPD VSimSDfarFields VSimEMfarFieldsGPU VSimEMgeometry VSimEM VSimMD VSimPDgeometryGPU VSimEMgpuPml VSimEMmalGPU VSimEMmirror VSimEM VSimMDoriginRadiatorPort VSimEM VSimMDperfectDispersion VSimPAport VSimEM VSimMDscatteringBox VSimEMscatteringBoxGPU VSimEMyeeGPU VSimEM

8.1. Macros Overview 119

Page 124: VSim In Depth

VSim In Depth, Release 8.2.1

8.2 Macros present in Version 7

8.2.1 Absorbing Box Macro File

This macro file can be imported to an input file with $ import DrudeDebyeLorentzDielectric.

This macro file is available to all packages.

This collection of macros will set up absorbers on all sides of the simulation domain. Also there are macros to setabsorbers correctly when periodic boundaries are present. This macro is encrypted and available with the VSimBaselicense. It can be imported to an input file with $ import absorbingBox For Cartesian simulations, or Cylindricalsimulations that exclude the axis region, the absorbingBox macro is appropriate. For cylindrical simulations in 2D, itmay be more appropriate to use the absorbingBoxCylAxis macro, which enforces periodicity in the third dimension,normally phi, 𝜑, and excludes absorbtion on the 𝑟 = 0 axis. Additionally there is the absSavBoxCylAxis, which usesabsAndSav particle sinks in place of absorbers.

The labelling of the faces, edges and corners is consistent across all macros contained in this macro file. See Labelsused for faces, edges and corners by the absorbing box macro..

Fig. 8.1: Labels used for faces, edges and corners by the absorbing box macro.

absorbingBox Macro

absorbingBox ( nx, ny, nz,per_x,per_y,per_z): Sets up fully absorbing boxes in any dimension. If per_x/y/z arespecified the faces that are periodic will not be absorbing.

120 Chapter 8. Macros

Page 125: VSim In Depth

VSim In Depth, Release 8.2.1

absorbingBox ( nx, ny, nz): Sets up fully absorbing boxes in any dimension, with no periodic boundaries.

absorbingBox Macro Parameters

nx: Number of cells in x direction.

ny: Number of cells in y direction.

nz: Number of cells in z direction.

per_x: Is the simulation periodic in x (True/False).

per_y: Is the simulation periodic in y (True/False).

per_z: Is the simulation periodic in z (True/False).

absAndEmitBox Macro

absAndEmitBox ( nx, ny, nz, per_x, per_y, per_z): Sets up absorbing and reemitting boxes in any dimension.Ifper_x/y/z are specified the faces that are periodic will not be absorbing/remitting.

absAndEmitBox Macro Parameters

nx: Number of cells in x direction.

ny: Number of cells in y direction.

nz: Number of cells in z direction.

per_x: Is the simulation periodic in x (True/False).

per_y: Is the simulation periodic in y (True/False).

per_z: Is the simulation periodic in z (True/False).

absorbingBoxCylAxis Macro

absorbingBoxCylAxis ( nz, nr, nphi): Sets up absorbing boxes with axis excluded, with phi periodic.

absorbingBoxCylAxis Macro Parameters

nz: Number of cells in 𝑧 direction (often NX).

ny: Number of cells in 𝑟 direction.

nz: Number of cells in 𝜑 direction.

absSavBoxCylAxis Macro

absSavBoxCylAxis ( nz, nr, nphi):

Sets up absorbing boxes that save particle information for reuse with axis excluded and with phi periodic.

8.2. Macros present in Version 7 121

Page 126: VSim In Depth

VSim In Depth, Release 8.2.1

absSavBoxCylAxis Macro Parameters

nz: Number of cells in 𝑧 direction (often NX).

ny: Number of cells in 𝑟 direction.

nz: Number of cells in 𝜑 direction.

8.2.2 Adimacros Macro File

This macro file can be imported to an input file with $ import adimacros.

This macro file is available to all packages.

adimacros: Alternating Direction Implicit (ADI) macros are used with the implicit Solver. The adimacros.macmacros are for use with the VSim Multifield feature. Macros from adimacros.mac that VSim users may findhelpful include

option‘adiUpdaters‘ for full ADI update.

dmAdiUpdaters: for full ADI update with domains requiring GridBoundary.

adiUpdaters

adiUpdaters (name, efld, bfld): defines all of the operators for the full ADI update. The adiUpdaters macro islocated in the file adimacros.mac.

Names start with p or m corresponding to P matrix and M matrix, respectively. Names end with the direction ofthe ADI. mult or solv refers to application or inversion of the matrix. The divergence preserving update appliesthese in the order:

• msolv

• pmult

• (add in current)

• psolv

• mmult

The curl steady state update applies these in the order:

• mmult

• pmult

• (add in current)

• psolv

• msolv

adiUpdaters macro parameters include:

• name: name assigned to the collection.

• efld: electric field

• bfld: magnetic field

122 Chapter 8. Macros

Page 127: VSim In Depth

VSim In Depth, Release 8.2.1

dmAdiUpdaters

dmAdiUpdaters (name, efld, bfld, bndry, inttype): defines all of the operators for the full ADI update for do-mains requiring GridBoundaries. This allows users to simulation EM with implicit methods for domains thatare circles, spheres, or cavities, for example. The dmAdiUpdaters macro is located in the file adimacros.mac.

Names start with p or m corresponding to P matrix or M matrix, respectively. Names end with the direction ofthe ADI. mult or solv refers to application or inversion of the matrix. The divergence preserving update appliesthese in the order:

• msolv

• pmult

• (add in current)

• psolv

• mmult

The curl steady state update applies these in the order:

• mmult

• pmult

• (add in current)

• psolv

• msolv

dmAdiUpdaters macro parameters

name: name assigned to the collection.

efld: electric field.

bfld: magnetic field.

bndry: name of the grid boundary.

inttype: the interiorness type; this should usually be deymittra.

8.2.3 Antennas Macro File

This macro file can be imported to an input file with $ import antennas.

This macro file is available with the VSimEM package.

This macro collections contains combinations of shape primitives to generate horn and parabolic antennnas, and adda history that will record far field data. There are two versions of this macro, one antennas is for use when doingcomputations on a CPU, the other antennasGPU is used for computations on a GPU. They retain the exact samefunctionality, however GPU and CPU macros cannot be mixed.

Horn Antenna Macro

hornAntenna (name,dir,ofx,ofy,ofz,ww,wh,wl,al,ah,aw,mt): defines a horn antenna with a rectangular aperture.

8.2. Macros present in Version 7 123

Page 128: VSim In Depth

VSim In Depth, Release 8.2.1

hornAntenna Macro Parameters

name: name of the horn antenna.

dir: Axial direction of the horn antenna.

ofx: Offset in X (m).

ofy: Offset in Y (m).

ofz: Offset in Z (m).

ww: Width of waveguide (m).

wh: Height of waveguide (m).

wh: Height of waveguide (m).

wl: Length of waveguide (m).

al: Length of aperture (m).

ah: Height of aperture (m).

aw: Width of aperture (m).

mt: Thickness of horn antnenna (m).

Parabolic Antenna Macro

parabolicAntenna (name,dir,ofx,ofy,ofz,dp,rd,mt): This macro defines a parabolic dish (no feed specified).

parabolicAntenna Macro Parameters

name: name of the parabolic dish.

dir: Axial direction of the parabolic dish.

ofx: Offset in X (m).

ofy: Offset in Y (m).

ofz: Offset in Z (m).

dp: Depth of the paraboloid (m).

rd: Radius of the paraboloid at the aperture (m).

mt: Thickness of horn antnenna (m).

Add Far Field History Macro

addFarFieldHistory (historyName,NUM_THETA,NUM_PHI,RS,NS,HIST_DELAY,FREQUENCY):Adds a history to compute the far field radiation pattern. Note that far fields must be added with the addFarFieldsmacro found in the farFields macro.

124 Chapter 8. Macros

Page 129: VSim In Depth

VSim In Depth, Release 8.2.1

addfarFieldHistory Macro Parameters

historyName: Name to give the history dataset.

NUM_THETA: The number of theta points in the far field.

NUM_PHI: The number of phi points in the far field.

RS: The Radius of the Kirchhoff sphere–must be larger than the geometry and any scatteringBox, butsmaller than any boundary conditions (most MALs protrude 1 wavelength into the simulation do-main).

NS: The number of the points in the discretization of the line integrals around the Kirchhoff sphere.

HIST_DELAY: Delay time before far field transformation begins.

FREQUENCY: The frequency at which the test device is operating.

Add Far Field History Power User Macro

addFarFieldHistoryPowerUser (historyName,emFieldName,NUM_THETA,NUM_PHI,RS,NS,HIST_DELAY,FREQUENCY,DFF,TFFMIN,TFFMAX,NTFAR,ANTENNA_X,ANTENNA_Y,ANTENNA_Z):This macro is intended for finding the radiation patterns of large scale structures. All parameters in computingthe history are available to the user to facilitate this. Note that far fields must be added with the addFarFieldsmacro found in the farFields macro.

This macro is encrypted and only available with the VSimEM license.

addfarFieldHistoryPowerUser Macro Parameters

historyName: Name of the history.

emFieldName: Name of the multifield.

NUM_THETA: The number of theta points in the far field.

NUM_PHI: The number of phi points in the far field.

RS: The Radius of the Kirchhoff sphere–must be larger than the geometry and any scatteringBox, butsmaller than any boundary conditions (most MALs protrude 1 wavelength into the simulation do-main).

NS: The number of the points in the discretization of the line integrals around the Kirchhoff sphere.

HIST_DELAY: Delay time before far field transformation begins.

FREQUENCY: The frequency at which the test device is operating.

DFF: Distance to the far field (normally set to 10 m).

TFFMIN: Time at which the far field starts being taken, at the far field. Normally(DFF+RS)/LIGHTSPEED + HIST_DELAY.

TFFMAX: Time at which the far field stops being taken, at the far field. Normally TFFMIN + 1/FRE-QUENCY.

NTFAR: Number of time points the far field is taken at. Normally 1.

ANTENNA_X: Center of the Kirchhoff sphere on the x axis, normally 0.

ANTENNA_Y: Center of the Kirchhoff sphere on the y axis, normally 0.

ANTENNA_Z: Center of the Kirchhoff sphere on the z axis, normally 0.

8.2. Macros present in Version 7 125

Page 130: VSim In Depth

VSim In Depth, Release 8.2.1

8.2.4 Average Macro File

This macro file can be imported to an input file with $ import average.

This macro file is available to all packages.

This collection of macros will calculate the trailing average or window average of any 1D or 3D field.

averageFieldWindow Macro

averageFieldWindow (FieldName,FieldOffset,Dimensionality,DUMP_PERIOD,DT,WinWidthSteps,WinWidthSec,lx,ly,lz,ux,uy,uz):Adds a field that is the window average of the field FieldName. A window average is an unweighted meanof the last n timesteps. The window’s width is specified in units of timesteps (WinWidthSteps) or seconds(WinWidthSec). The unused window width argument must be set to none. Care must be taken with windowsthat are longer than the dump period; the average field will only dump when it has completed, which will notnecessarily be every dump. After setting up all average fields, make a call to the appendAveSteps macro, below,to include the average fields in the updateStepOrder.

averageFieldWindow Macro Parameters

FieldName: Name of the field to be averaged

FieldOffset: Offset of the field to be averaged. Can be none, edge, center, face, or edge4v.

Dimensionality: Integer number of components in field, 1 or 3

DUMP_PERIOD: Number of steps between dumps

DT: Length of timestep

WinWidthSteps: Time length of window in decimal timesteps; may be float or integer (e.g. 19.9); Setto none if using WinWidthSec

WinWidthSec: Time length of window in seconds; Set to none if using WinWidthStep.

lx: Lower x integer cell number

ly: Lower y integer cell number

lz: Lower z integer cell number

ux: Upper x integer cell number

uy: Upper y integer cell number

uz: Upper z integer cell number

averageField Macro

averageField (FieldName,FieldOffset,Dimensionality,DT,tau,lx,ly,lz,ux,uy,uz): Adds a field that is the trail-ing average of the field FieldName. A trailing average is the mean of all previous timesteps but weightedexponentially toward more recent values. It is also known as a Kalman filter, or low-pass filter. The trailingaverage is given by the equation,

��𝑖 =

(1 − 𝛿𝑡

𝜏

)𝑛𝑖−1 +

𝛿𝑡

𝜏𝑛𝑖

126 Chapter 8. Macros

Page 131: VSim In Depth

VSim In Depth, Release 8.2.1

where 𝑖 is the current timestep, 𝑛𝑖 is the field value at the current timestep, and 𝛿𝑡 is DT, the length of atimestep. The trailing factor, 𝜏 , is specified by the user. After all average fields are set up, make a call to theappendAveSteps macro, below, to include the average fields in the updateStepOrder.

averageField Macro Parameters

FieldName: Name of the field to be averaged.

FieldOffset: Offset of the field to be averaged.

Dimensionality: Integer number of components in field, 1 or 3

DT: Length of timestep

tau: Trailing factor in seconds (e.g. 1.9e-10)

lx: Lower x integer cell number

ly: Lower y integer cell number

lz: Lower z integer cell number

ux: Upper x integer cell number

uy: Upper y integer cell number

uz: Upper z integer cell number

appendAveSteps Macro

appendAveSteps (updateStepList): This macro helps solve the problem of the updateStepOrder variable, whichcan optionally be hard coded by the user to specify an order of update steps that differs from the natural orderin the PRE code. If the user has specified the updateStepOrder, then the averaging fields must be added to thelist or they will never update. The averageField UpdateStep must be appended to updateStepOrder after theupdateStep for whatever field you are averaging. Call this macro from within the <MultiField> block.

To use this macro,

1. Assign your updateStepOrder to the variable updateStepList; make the list without brackets. If youhave set up your multifield with macros like yee, this will have been done automatically. Example:updateStepList = step1 step2 step3

2. Call the macro: $ updateStepList = appendAveSteps(updateStepList)

3. Put updateStepList into updateStepOrder: updateStepOrder = [updateStepList]

appendAveSteps Macro Parameters

updateStepList: List of pre-existing update steps without brackets

Example Usage of Average Macros

averageField(testField1D,none,1,DT,8.e-11,0,0,0,NX,NY,NZ)averageFieldWindow(testField1D,none,1,DUMP_PERIOD,DT,19.9,none,0,0,0,NX,NY,NZ)averageField(testField,edge,3,DT,9.e-11,0,0,0,NX,NY,NZ)averageFieldWindow(testField,edge,3,DUMP_PERIOD,DT,none,1.8e-10,0,0,0,NX,NY,NZ)

8.2. Macros present in Version 7 127

Page 132: VSim In Depth

VSim In Depth, Release 8.2.1

# Update steps<UpdateStep step1>

toDtFrac = 1.updaters = [testUpdate]messageFields = [testField]

</UpdateStep>

<UpdateStep step2>toDtFrac = 1.updaters = [testUpdate1D]messageFields = [testField1D]

</UpdateStep>

$ updateStepList = step1 step2$ updateStepList = appendAveSteps(updateStepList)updateStepOrder = [updateStepList]

</MultiField>

8.2.5 Basic EM Macro File

This macro file can be imported to an input file with $ import antennas.

This macro file is available to all packages.

This collection of macros is meant to handle basic EM fields. It will establish the updaters and update steps to run theyee algorithm. The user must define the electric and magnetic fields themselves.

basicEM Macro

basicEM (elecfield,magfield,nx,ny,nz): Define the fields, updaters and update steps for the regular update methodon a Yee mesh. Designed to replace the old kind = yeeEmField. This requires the user to define the electric andmagnetic fields so initial and boundary can be defined. This macro must set the update step order.

basicEM (elecfield,magfield,gridboundary,nx,ny,nz): Version of macro for use with gridboundary.

basicEM (elecfield,magfield,nx,ny,nz,plx,ply,plz,pux,puy,puz): Version of macro for use with the PmlRegion.

basicEM Macro Parameters

elecfield: Name of the electric field.

magfield: Name of the magnetic field.

nx: Number of cells in the X-direction.

ny: Number of cells in the Y-direction.

nz: Number of cells in the Z-direction.

gridboundary: The name of the grid boundary.

plx: Number of pml cells in lower X.

ply: Number of pml cells in lower Y.

pyz: Number of pml cells in lower Z.

128 Chapter 8. Macros

Page 133: VSim In Depth

VSim In Depth, Release 8.2.1

pux: Number of pml cells in upper X.

puy: Number of pml cells in upper Y.

puz: Number of pml cells in upper Z.

Example of basicEM Macro

<EmField yeeEmField>kind = emMultiField

<Field YeeElecField>numComponents = 3offset = edge

</Field>

<Field YeeMagField>numComponents = 3offset = face

</Field>

basicEM(YeeElecField,YeeMagField,sphere,NX,NY,NZ)</EmField>

8.2.6 Crank-Nicholson Macro File

This macro file can be imported to an input file with $ import cnmacros.

This macro file is available to all packages.

This collection of macros is used for using the Crank-Nicholson implicit solve for advancing the electromagneticfields.

Crank-Nicholson Matrix Macro

cnMatrix (name, sign): Matrix for a Crank-Nicholson solver for EM. This does not work well at large values ofimplicitness for the standard reasons when solving hyperbolic equations.

cnMatrix Parameters

name: Name of the matrix.

sign: 1 for the explicit or application part, -1 for the implicit or solve part.

Crank-Nicholson Epetra Updaters Macro

cnEpetraUpdaters (): Define the explicit and implicit updaters needed for the Crank-Nicolson update of the EMfield. Assumes that the fields being updated are edgeElec and faceMag.

This macro takes no arguments.

8.2. Macros present in Version 7 129

Page 134: VSim In Depth

VSim In Depth, Release 8.2.1

Crank-Nicholson EM Field Macro

cnEmFieldAlgorithm (withNodalFields): This macros inserts the Crank-Nicholson update. It assumes thatedgeElec and faceMag have been defined. It defines any fields needed for just this algorithm.

cnEmFieldAlgorithm Parameters

withNodalFields: whether to create and update nodalE and nodalB. This is set to nonzero to beused with particles. With large implicitness, one may need to set maxcellxing for the particles.

8.2.7 Deymittra Macro File

This macro file can be imported to an input file with $ import deymittra.

This macro file is available to to the VSimMD, VSimEM or VSimPD packages.

This is a general macro file that contains multiple macros.

dmYee Macro

dMYee (elecfield, magfield, gridbndry, nx, ny, nz): defines the fields, updaters and update steps for the Dey-Mittracut cell method on a Yee mesh. This macro also sets up interpolation to use the Yee field (edge for E and facefor B). The dMYee macro is located in the file deymittra.mac.

Since this macro defines updates, be aware of the order in case boundary updaters are to be added:

• step1.0: the first half B update.

• step2.0: the full E update

• step3.0: the second half B update

The dMYee macro is compatible with the applyPML macro from pml.mac.

dMYee Macro Parameters

elecfield: name of the electric field.

magfield: name of the magnetic field.

gridbndry: name of the grid boundary.

nx: number of cells in x direction.

ny: number of cells in y direction.

nz: number of cells in z direction.

Dey Mittra Yee Macro

deyMittraYee (elecfield, magfield, rhojfield, gridbndry,nx, ny, nz): Define the fields, updaters and update stepsfor the Dey-Mittra cut cell method on a Yee mesh. This macro also sets up interpolation to use the Yee field(edge for E and face for B) Since this macro defines updates the user be aware of the order in case they with toadd boundary updaters. step1 - the first half B update step2 - the full E update step3 - the second half B update

130 Chapter 8. Macros

Page 135: VSim In Depth

VSim In Depth, Release 8.2.1

deyMittraYee Macro Parameters

elecfield: name of the electric field.

magfield: name of the magnetic field.

rhojfield: name of the charge density and current field.

gridbndry: name of the grid boundary.

nx: number of cells in x direction.

ny: number of cells in y direction.

nz: number of cells in z direction.

deyMittraYeeInterpol Macro

deyMittraYeeInterpol (elecfield, magfield, rhojfield, gridbndry, nx, ny, nz): defines the fields, updatersand update steps for the Dey-Mittra cut cell method on a Yee mesh, including the new constrained fieldsin the conductors needed for improved interpolation. The dMittraYeeInterpol macro is located in the filedeymittra.mac.

Since this macro defines updates, be aware of the order in case boundary updaters are to be added:

step1: first half B update

step2: full E update

step2.5: constrained field updater

step3: second half B update

deyMittraYeeInterpol Macro Parameters

elecfield: name of the electric field.

magfield: name of the magnetic field.

rhojfield: name of the charge density and current field.

gridbndry: name of the grid boundary.

nx: number of cells in x direction.

ny: number of cells in y direction.

nz: number of cells in z direction.

8.2.8 Dielectric Macro File

This macro file can be imported to an input file with $ import dielectric.

This macro file is available to the VSimEM package.

This collection of macros can be used to define a dielectric with a user defined profile and permittivity, or lossydielectric, with a user defined profile, permittivity and conductivity. These macros are only compatible with macrogenerated multifields (e.g. with the yee macro) There are two versions of this macro, dielectric and dielectricGPU.They have the same functionality, however dielectric is meant for simulations run on a CPU and dielectricGPU forsimulations run on a GPU. Note that GPU and CPU macros cannot be mixed

8.2. Macros present in Version 7 131

Page 136: VSim In Depth

VSim In Depth, Release 8.2.1

Add Dielectric Macro

addDielectric (dielectricProfile,name): Adds a dielectric with the profile specified.

addDielectric Macro Parameters

dielectricProfile: Spatial profile of relative permittivity of the dielectric as a function of x,y,z.

name: Name of the dielectric.

Add Lossy Dielectric Macro

addLossyDielectric (name,PERMITTIVITY,CONDUCTIVITY,lx,ly,lz,ux,uy,uz): This macro defines alossy dielectric in the region defined.

addLossyDielectric Macro Parameters

name: Name of the lossy dielectric.

PERMITIVITY: Permittivity of the dielectric.

CONDUCTIVITY: Conductivity of the lossy dielectric.

lx: Lower bound of the dielectric in the X direction.

ly: Lower bound of the dielectric in the Y direction.

lz: Lower bound of the dielectric in the Z direction.

ux: Upper bound of the dielectric in the X direction.

uy: Upper bound of the dielectric in the Y direction.

uz: Upper bound of the dielectric in the Z direction.

Example usage:

addDielectric(boxDielectric, 1 + (EPSILON_R-1)*geoBoxP(x,y,z,5*DX,5*DY,5*DZ))# The geoBoxP() evaluates to one where the point x,y,z is inside the box geometryand 0 outside, so "1+" ensures vacuum relative permittivity outside the box..

$ EPSILON_SALT_WATER = 32.$ SIGMA_SALT_WATER = 0.1<function someGeometry(x,y,z)>

H(x-x1)*H(x2-x)*H(y-y1)*H(y2-y)</function><function epsilonrelative(x,y,z)>

1+(EPSILON_SALT_WATER-1)*someGeometry(x,y,z)</function><function sigma(x,y,z)>

SIGMA_SALT_WATER*someGeometry(x,y,z)</function>addLossyDielectric(lossyDiel,epsilonrelative(x,y,z),sigma(x,y,z),XBGN,YBGN,ZBGN,XEND,→˓YEND,ZEND)

132 Chapter 8. Macros

Page 137: VSim In Depth

VSim In Depth, Release 8.2.1

8.2.9 Drude, Debye and Lorentz Materials Macro File

This macro file can be imported to an input file with $ import DrudeDebyeLorentzDielectric.

This macro file is available with the VSimEM package.

This macro file contains macros to assist in the creation of a frequency dependant dielectric following the Drude,Debye Relaxation, and/or Lorentz Resonant Models.

In these models, the total displacement and conduction current will be the following

𝐽𝑡𝑜𝑡𝑎𝑙 = 𝐽∞ + 𝐽𝐷𝑟𝑢𝑑𝑒𝐷𝑒𝑏𝑦𝑒 + Σ𝐽𝐿𝑜𝑟𝑒𝑛𝑡𝑧

[−𝑖𝜔𝜖(𝜔) + 𝜎(𝜔)]𝐸 = [−𝑖𝜔𝜖𝑅∞𝜖0 + 𝜎∞ + (𝜎𝑆𝑡𝑎𝑡𝑖𝑐−𝜎∞)(1−𝑖𝜔𝑡𝑐𝑜𝑙𝑙𝑖𝑠𝑖𝑜𝑛)

+ Σ𝐿−𝑖𝜔𝛼𝐿

(𝜔2𝐿−𝜔2−𝑖𝜔Γ𝐿)

]𝐸

There are 10 macros, 3 are mandatory (createRegion, initialize, update), and 7 are optionally usedto control the material properties (setInfLimits, SetAnalyticBackground, setDrudeByCarrier,setDrudeByConductance, setDebye, setLorentzByCarrier, setLorentzByConductanceRate).Their calling sequence is listed below, with respect to each other, and the other blocks in the input file. More detail oneach of the calls follows in the discussion.

Input file structure

<Multifield ...>

<Field ...>s and <FieldUpdater ...>s for other physics

createRegion_DDLD(edgeEname,objectName,nxbgn,nybgn,nzbgn,nxend,nyend,nzend,timeStep)

### OPTIONAL, NEITHER, EITHER, OR BOTH ###setAnalyticBackground_DDLD(epsRelExpression,sigmaExpression)setInfLimits_DDLD(epsRelInf,sigmaInf)

### OPTIONAL, AT MOST ONE OF THESE ###setDrudeByCarrier_DDLD(collisionTimeScale,carrierDensity,carrierCharge,carrierMass)setDrudeByConductance_DDLD(collisionTimeScale,sigmaStatic)setDebye_DDLD(relaxTime,epsRelStatic)

### OPTIONAL, MULTIPLE CALLS ALLOWED ###addLorentzByCarrier_DDLD(freqL,gammaL,carrierDensity,carrierCharge,carrierMass)addLorentzByConductanceRate_DDLD(freqL,gammaL,alphaL)

initialize_DDLD()

more <Fields ...>s and <FieldUpdater ...>s representing other physics

<UpdateStep ...>s for other physics, up to and including<UpdateStep Ampere> and any E field Boundary Conditions

update_DDLD()

more <UpdateStep ...>s for other physics

</Multifield>

8.2. Macros present in Version 7 133

Page 138: VSim In Depth

VSim In Depth, Release 8.2.1

Create DDLD Region Macro

createRegion_DDLD (edgeEname,objectName,nxbgn,nybgn,nzbgn,nxend,nyend,nzend,timeStep):Specifies that DDLD updaters will be applied in the region specified.

To get started, the user must call the createRegion_DDLD macro somewhere near the beginning of the<MultiField ...> block. This call requires the name of the edge electric <Field ...> used in theAmpere update, the name of the dielectric, as constructed in a <GridBoundary ...> object. It also requiresthe grid index limits over which to apply this model, and the time step.

createRegion_DDLD Macro Parameters

edgeEname: Name of the (edge centred) E field to be used by the updater.

objectName: Name of the <GridBoundary ...> object representing the DDLD.

nxbgn: The index of the lower x extent for the DDLD updates.

nybgn: The index of the lower y extent for the DDLD updates.

nzbgn: The index of the lower z extent for the DDLD updates.

nxend: The index of the upper x extent for the DDLD updates.

nyend: The index of the upper y extent for the DDLD updates.

nzend: The index of the upper z extent for the DDLD updates.

timeStep: The timestep being used by the yee algorithm.

Set Analytic Background Material Macro (Optional)

setAnalyticBackground_DDLD (epsRelExpression,sigmaExpression): This algorithm does not treat or alterdielectric or conductance outside the user-provided grid index range, and it is required that the Ampere updatewithin the user-provided index range is that of vacuum, e.g., 𝜖𝑟 = 1 (epsRel=1) and 𝜎 = 0 (sigma=0), whetheror not that is actually the case. In particular, if in reality, the DDLD material is embedded in a material otherthan vacuum, this is treated with a call to setAnalyticBackground_DDLD, which creates a frequency-independent material within the user-specified index range, surrounding the DDLD’s <GridBoundary> ob-ject. An analytic function of space is used to specify this background material’s epsRel and sigma. The call tosetAnalyticBackground_DDLD should be made immediately after the call to createRegion_DDLDcall, and before any other set or add calls..

Set Analytic Background Material Macro Parameters

epsRelExpression: Relative permittivity. If using a function, then specify the function name asfunctionName(x,y,z), or expression string.

sigmaExpression: Conductivity. If using a function, then specify the function name asfunctionName(x,y,z), or expression string, in 1/(ohms*meters).

Set Infinite Frequency Limit Macro (Optional)

setInfLimits_DDLD (epsRelInf,sigmaInf): As a precaution to ensure stable behavior, the model must have welldefined high-frequency limits of the dielectric and conductance, 𝜖𝑟∞ (epsRelInf) and 𝜎∞ (sigmaInf).

134 Chapter 8. Macros

Page 139: VSim In Depth

VSim In Depth, Release 8.2.1

The defaults for these are vacuum, 𝜖𝑟∞ = 1 and 𝜎∞ = 0. But if residual high frequency dielectric or con-ductance is desired, in order to better fit the desired behavior in the frequency range of the simulation, callsetInfLimits_DDLD to override the defaults. The call to setInfLimits_DDLD should be made im-mediately after the call to createRegion_DDLD and possibly setAnalyticBackground_DDLD, andbefore any other set or add calls. Also note that if a subsequent call to setDebye_DDLD is made, the value ofsigmaInf will be overwritten.

Set Infinite Frequency Limit Macro Parameters (Optional)

epsRelInf: Relative permittivity limit at high frequencies. If using a function, then specify the func-tion name as functionName(x,y,z), or expression string.

sigmaInf: Conductance limit at high frequencies, in 1/(ohms*meters).

Set Zero Frequency Limit - the Primary Options

In general, the low frequency behavior of the dielectric is different from the high freuqency limit, and is specificedwith either a Drude model, or a Debye Relaxation Model, or neither, but not both. The Drude model focuses on thezero frequency limit of conductance, while the Debye Relaxation focuses on the zero frequency limit of dielectric.In the formula above, if we assume no zero-frequency Lorentz resonances, the zero frequency limit of conductanceis indeed, sigmaStatic, from the Drude term. The zerofrequency limit of dielectric has contriubtions for all terms,however, and is

epsRelStatic = epsRelInf - (sigmaStatic-sigmaInf)*collisionTime/eps0 + SumL{ alphaL/𝜔2𝐿 /eps0 }

𝜖𝑟𝑠𝑡𝑎𝑡𝑖𝑐 = 𝜖𝑟∞ − (𝜎𝑠𝑡𝑎𝑡𝑖𝑐 − 𝜎∞) · 𝑡𝑐𝑜𝑙𝑙𝑖𝑠𝑖𝑜𝑛/𝜖0 + Σ𝐿𝛼𝐿

𝜔2𝐿𝜖0

Drude Model, by carrier macro

setDrudeByCarrier_DDLD (collisionTimeScale,carrierDensity,carrierCharge,carrierMass)

The Drude model assumes unbound charge carriers which undergo collisions, resulting in a frequencydependant conduction current. sigmaStatic is the static (zero-frequency) limit of the conductance in thismodel. A call to setDrudeByCarrier_DDLD will set up the drude model parameters.

When this call is made, the zero frequency limit of conductance in the Drude Model is computed, accord-ing to the formula

sigmaStatic = collisionTime*(carrierDensity*carrierCharge^2/carrierMass)

Drude Model, by carrier macro parameters

collisionTime: Mean collision time in seconds

carrierDensity: Number density of charge carriers in 1/meters^3

carrierCharge: Unitless multiplier of the electron charge, 𝑒

carrierMass: Unitless multiplier of the electron mass, 𝑚𝑒

8.2. Macros present in Version 7 135

Page 140: VSim In Depth

VSim In Depth, Release 8.2.1

Drude Model, by conductance macro

setDrudeByConductance_DDLD (collisionTimeScale,sigmaStatic)

Alternately, the user may choose to setup the drude model directly with the resultant conductance, thusavoiding the need to know information about the carriers. A call to setDrudeByConductance_DDLDwill do this.

Drude Model, by conductance macro parameters

collisionTime: Mean collision time, in seconds

sigmaStatic: ‘Static’ conductance in 1/(ohms*meters)

Debye Model

setDebye_DDLD (relaxTime,epsRelStatic)

The Debye Relaxation Model assumes bound charge carriers whose dielectric response relaxes at higherfrequencies. Since bound charges cannot create conduction current, sigmaStatic=0 will be enforced bythis call. The user provides epsRelStatic, the static (zero-frequency) limit of the dielectric, in the absenceof any Lorentz resonances. the user also specifies relaxTime, the time scale at which dielectric responserelaxes from epsRelStatic to epsRelInf. A call to setDebye_DDLD will set up the Debye RelaxationModel.

This model will reset collisionTime = relaxTime, and sigmaInf=(epsRelStatic-epsRelInf)/relaxTime, inorder to convert the Drude term to the Debye Relaxation Model. This formulation then allows the combi-nation of Infinity-Limit and Drude Terms to be recast as

[-i* 𝜔 *eps( 𝜔 ) + sigma( 𝜔 ) ]*E = -i * 𝜔 *[ epsRelInf + (epsRelStatic-epsRelInf)/(1-i* 𝜔*relaxTime) ]*E

[−𝑖𝜔𝜖(𝜔) + 𝜎(𝜔)]𝐸 = −𝑖𝜔[𝜖𝑅∞ + (𝜖𝑅𝑆𝑡𝑎𝑡𝑖𝑐 − 𝜖𝑅∞)/(1 − 𝑖𝜔𝑡𝑟)]𝐸

Debye Model Parameters

relaxTime: Debye relaxation time, in seconds

epsRelStatic: Unitless relative dielectric permitivity in the static limit

Intermediate Frequency Behavior (Optional)

The intermediate frequency behavior can optionally include one or more Lorentz Resonannces. Theunusual case of a zero frequency Lorentz resonance, 𝑓𝐿 = 0, would be equivalent to a Drude Model,and so would normally be handled using that model. However, it is allowed to produce multiple Drudeterms in such a manner if such unusual behavior is actually desired. A zero line width, Γ𝐿 = 0, is alsopermitted, although such a circumstance would also be considered unusual.

Lorentz Model, by Carrier Macro

addLorentzByCarrier_DDLD: (freqL,gammaL,carrierDensity,carrierCharge,carrierMass)

136 Chapter 8. Macros

Page 141: VSim In Depth

VSim In Depth, Release 8.2.1

The Lorentz Model assumes bound charge carriers whose response is resonant at some finite frequency,freqL, with a line width of the resonance given by gammaL. A Lorentz resonance will be added to theinfinite and zero frequency limits with a call to addLorentzByCarrier_DDLD.

When this call is made, these parameters are used to produce the conductance rate in the Lorentz Current,according to

𝛼𝐿 = carrierDensity*carrierCharge^2/carrierMass

Lorentz Model, by Carrier Macro Parameters

freqL: Lorentz frequency in Hertz, = 𝜔𝐿/(2𝜋)

gammaL: Lorentz gamma in 1/seconds

carrierDensity: Number density of charge carriers in 1/meters^3

carrierCharge: unitless multiplier of the electron charge, 𝑒

carrierMass: unitless multiplier of the electron mass, 𝑚𝑒

Lorentz Model, by Conductance Rate

addLorentzByConductanceRate_DDLD (freqL,gammaL,alphaL)

Alternately, the user may choose to setup the Loretnz resonance directly with the resultant con-ductance rate, thus avoiding the need to know information about the carriers. A call toaddLorentzByConductanceRate_DDLD will do this.

Lorentz Model, by Conductance Rate Parameters

freqL Lorentz Frequency (𝑓𝐿) in Hertz, = 𝜔𝐿

(2𝜋)

gammaL Lorentz Gamma (Γ𝐿) in 1/seconds

alphaL Lorentz Alpha (𝛼𝐿) in 1/(ohms*meters*seconds)

Initialization (Required)

initialize_DDLD ()

Immediately after create, set, and add calls, the model must instantiate and initialize its internal fields.This is done with a call to initialize_DDLD(), which has no arguments.

If the input file is making use of the updateStepOrder attribute, instead of order of appearence in theinput file, then the single Initial update step, initializeDDLD, must be inserted in the proper locationwithin the list, before any of the <UpdateStep> s. The particular placement with respect to any otherInitialUpdateSteps is not important.

Update Macro (Required)

update_DDLD ()

8.2. Macros present in Version 7 137

Page 142: VSim In Depth

VSim In Depth, Release 8.2.1

The actual update of the DDLD is done with the update_DDLD() call, which has no arguments. The callmust be placed just folowing the Ampere <UpdateStep ...> and any additional <UpdateStep...> s which act as boundary conditions for the electric field update.

If the input file is making use of the updateStepOrder attribute, instead of order of appearence in theinput file, then the single update step, updateDDLD(), must be inserted in the proper location withinthe list, after the Ampere and electric field boundary condition update steps.

Communication and Parallelization

The DDLD materials are a point model, so no communication of the internal fields is necessary acrossparallel processes. Thus while there are many <FieldUpdater ...> s involved in the initializationand update, they are all placed together in single steps, which have empty messageFields attributes.

Stability

The algorithm is implicit and so no additional Courant conditions are introduced on the time step. How-ever, instabiity is still possible if the conductivity at some frequency between zero and 2/dt were to benegative. Some limiters are in place to help prevent such a circumstance should the user attempt to inputnegative conductance, for example. Similarly, there are limiters to help prevent relative dielectric belowunity. Thus, these macros are not capable of treating negative index of refraction, for example, and shouldnot be attempted to be used for such purposes.

8.2.10 em Macro File

This macro file can be imported to an input file with $ import em.

This macro file is available to all packages.

This collection of macros consists of some algorithms to help with electromagnetic simulations.

computeCurlDt Macro

computeCurlDt (name, restorefield, readfield, writefield, multfac):

A macro to compute the curl of a vector times dt for doing an EM update. Updates over the entire computationalregion.

Note that this macro requires the variables NX, NY, NZ, DT, DX, DY and DZ.

computeCurlDt Macro Parameters

name: Name of the updater to compute the curl from.

restoreField: Name of field from which to restore updater time upon restart.

readField: The field to copy from.

writefield: The field to copy to.

multfac: The factor by which to multiply dt before updating. This is ordinarily set to one.

138 Chapter 8. Macros

Page 143: VSim In Depth

VSim In Depth, Release 8.2.1

constCurlDt Macro

constCurlDt (name, restorefield, readfield, writefield, multfac):

Compute the curl of a vector times a factor. The factor is set to the appropriate fraction of DT.

Note that this macro requires the variables NX, NY, NZ, DT, DX, DY and DZ.

constCurlDt Macro Parameters

name: Name of the updater to compute the curl from.

restoreField: Name of field from which to restore updater time upon restart.

readField: The field to copy from.

writefield: The field to copy to.

multfac: The factor by which to multiply dt before updating. This is ordinarily set to one.

Yee Macro

Yee (elecfield, magfield, nx, ny, nz):

Define the fields, updaters and update steps for the regular update method on a Yee mesh. This macro also sets upinterpolation to use the Yee field (edge for E and face for B). Since this macro defines updates the user be aware of theorder in case they with to add boundary updaters.

step1.0 - the first half B update step2.0 - the full E update step3.0 - the second half B update step4.1 - thenodal E update step4.2 - the nodal B update

init_step1.1 - the nodal E restore init_step1.2 - the nodal B restore

Yee Macro Parameters

elecfield: Name of the electric field.

magfield: Name of the magnetic field.

nx: The number of cells in the X direction.

ny: The number of cells in the Y direction.

nz: The number of cells in the Z direction.

8.2.11 Electrostatic Grid Boundary Macro File

This macro file can be imported to an input file with $ import esGridBoundary.

This macro file is available to the VSimEM, VSimSD, or VSimPD packages.

This collection of macros consists of tools for solving dirichlet electrostatic boundaries and computing node-centeredLaplacians.

8.2. Macros present in Version 7 139

Page 144: VSim In Depth

VSim In Depth, Release 8.2.1

nodeLaplacian Macro

nodeLaplacian (name, gb, md, lbx, lby, lbz, ubx, uby, ubz, comp, fld, fcomp, ri, ci, dcoeff, xcoeff, ycoeff, zcoeff):

Macro for node-centered Laplacian with grid boundaries.

nodeLaplacian Macro Parameters

name: The base name of the boundary condition.

gb: The grid boundary name.

md: The minimum dimension needed for this boundary condition.

lbx: Lower bound in the x direction.

lby: Lower bound in the y direction.

lbz: Lower bound in the z direction.

ubx: Upper bound in the x direction.

uby: Upper bound in the y direction.

ubz: Upper bound in the z direction.

comp: The component (row of the matrix) being filled.

fld: The name of the field used to fill the associated source (RHS) vector.

fcomp: The component of the field.

ri: The interiorosity of points whose corresponding rows in the matrix are to be filled.

ci: The interiorosity of points whose corresponding columns in the matrix can be filled.

dcoeff: Diagonal coefficient.

xcoeff: Coefficient for x offset stencils.

ycoeff: Coefficient for y offset stencils.

zcoeff: Coefficient for z offset stencils.

coordProdNodeLaplacian Macro

coordProdNodeLaplacian (name, gb, md, lbx, lby, lbz, ubx, uby, ubz, comp, fld, fcomp, ri, ci, scl, func):

Macro for node-centered Laplacian with grid boundaries in a coordinate product (coordProd) grid.

coordProdNodeLaplacian Macro Parameters

name: The base name of the boundary condition.

gb: The grid boundary name.

md: The minimum dimension needed for this boundary condition.

lbx: Lower bound in the x direction.

lby: Lower bound in the y direction.

lbz: Lower bound in the z direction.

140 Chapter 8. Macros

Page 145: VSim In Depth

VSim In Depth, Release 8.2.1

ubx: Upper bound in the x direction.

uby: Upper bound in the y direction.

ubz: Upper bound in the z direction.

comp: The component (row of the matrix) being filled.

fld: The name of the field used to fill the associated source (RHS) vector.

fcomp: The component of the field.

ri: The interiorosity of points whose corresponding rows in the matrix are to be filled.

ci: The interiorosity of points whose corresponding columns in the matrix can be filled.

scl: The scaling factor by which all matrix elements will be multiplied.

func: The expression for the function defining the value.

nodeFuncLaplacian Macro

nodeFuncLaplacian (name, gb, md, lbx, lby, lbz, ubx, uby, ubz, comp, fld, fcomp, ri, ci, xcoeff, ycoeff, zcoeff,func):

Macro for node-centered Laplacian with grid boundaries using a STFunc for the coefficient.

nodeFuncLaplacian Macro Parameters

name: The base name of the boundary condition.

gb: The grid boundary name.

md: The minimum dimension needed for this boundary condition.

lbx: Lower bound in the x direction.

lby: Lower bound in the y direction.

lbz: Lower bound in the z direction.

ubx: Upper bound in the x direction.

uby: Upper bound in the y direction.

ubz: Upper bound in the z direction.

comp: The component (row of the matrix) being filled.

fld: The name of the field used to fill the associated source (RHS) vector.

fcomp: The component of the field.

ri: The interiorosity of points whose corresponding rows in the matrix are to be filled.

ci: The interiorosity of points whose corresponding columns in the matrix can be filled.

xcoeff: Coefficient for x offset stencils.

ycoeff: Coefficient for y offset stencils.

zcoeff: Coefficient for z offset stencils.

func: The expression for the STFunc defining the value of the coefficient.

8.2. Macros present in Version 7 141

Page 146: VSim In Depth

VSim In Depth, Release 8.2.1

gridBoundaryDirichletBC Macro

gridBoundaryDirichletBC (name, gb, md, lbx, lby, lbz, ubx, uby, ubz, comp, exp, scl):

Macro for setting Dirichlet boundary conditions on a grid boundary in electrostatic solves with node-centered fields.

gridBoundaryDirichletBC Macro Parameters

name: The base name of the boundary condition.

gb: The grid boundary name.

md: The minimum dimension needed for this boundary condition.

lbx: Lower bound in the x direction.

lby: Lower bound in the y direction.

lbz: Lower bound in the z direction.

ubx: Upper bound in the x direction.

uby: Upper bound in the y direction.

ubz: Upper bound in the z direction.

comp: The component (row of the matrix) being filled.

exp: The expression for the function defining the value.

scl: The scaling applied to all matrix and vector entries.

exteriorGridBoundaryDirichletBC Macro

exteriorGridBoundaryDirichletBC (name, gb, md, lbx, lby, lbz, ubx, uby, ubz, comp, exp, scl):

Macro for solving points exterior to a grid boundary defined Dirichlet boundary condition in electrostatic solves withnode-centered fields.

exteriorGridBoundaryDirichletBC Macro Parameters

name: The base name of the boundary condition.

gb: The grid boundary name.

md: The minimum dimension needed for this boundary condition.

lbx: Lower bound in the x direction.

lby: Lower bound in the y direction.

lbz: Lower bound in the z direction.

ubx: Upper bound in the x direction.

uby: Upper bound in the y direction.

ubz: Upper bound in the z direction.

comp: The component (row of the matrix) being filled.

exp: The expression for the function defining the value.

142 Chapter 8. Macros

Page 147: VSim In Depth

VSim In Depth, Release 8.2.1

scl: The scaling applied to all matrix and vector entries.

8.2.12 Electrostatic Solve Open Boundary Macro

This macro file can be imported to an input file with $ import esSolveOpenBdry.

This macro file is available to all packages.

This macro file consists of tools for solving open electrostatic boundary conditions.

surfaceCharge Macro

surfaceCharge (name, md, lbx, lby, lbz, ubx, uby, ubz, mcomp, rfld, rcomp, wfld, wcomp, coeff, offx, offy, offz):

Macro to calculate the boundary screening charge.

surfaceCharge Macro Parameters

name: The base name of the field updater.

md: The minimum dimension needed for this boundary condition.

lbx: Lower bound in the x direction.

lby: Lower bound in the y direction.

lbz: Lower bound in the z direction.

ubx: Upper bound in the x direction.

uby: Upper bound in the y direction.

ubz: Upper bound in the z direction.

comp: The component (row of the matrix) being filled.

rfld: The name of the input field from which to calculate the screening charge.

rcomp: The component of the read field.

wfld: The name of the input field from which to write the screening charge.

wcomp: The component of the write field.

coeff: Diagonal coefficient.

offx: X-offset of the input vector.

offy: Y-offset of the input vector.

offz: Z-offset of the input vector.

surfacePotential Macro

surfacePotential (name, md, lbx, lby, lbz, ubx, uby, ubz, srcLbx, srcLby, srcLbz, srcUbx, srcUby, srcUbz, dn,rfld, rcomp, wfld, wcomp, rTFld, alpha):

Macro to calculate the potential due to the boundary screening charge.

8.2. Macros present in Version 7 143

Page 148: VSim In Depth

VSim In Depth, Release 8.2.1

surfaceCharge Macro Parameters

name: The base name of the field updater.

md: The minimum dimension needed for this boundary condition.

lbx: Lower bound in the x direction over which this is applied.

lby: Lower bound in the y direction over which this is applied .

lbz: Lower bound in the z direction over which this is applied.

ubx: Upper bound in the x direction over which this is applied.

uby: Upper bound in the y direction over which this is applied.

ubz: Upper bound in the z direction over which this is applied.

srcLbx: Lower bound in the x direction where the source is located.

srcLby: Lower bound in the y direction where the source is located.

srcLbz: Lower bound in the z direction where the source is located.

srcUbx: Upper bound in the x direction where the source is located.

srcUby: Upper bound in the y direction where the source is located.

srcUbz: Upper bound in the z direction where the source is located.

dn: Direction.

rfld: The name of the input field from which to calculate the potential.

rcomp: The component of the read field.

wfld: The name of the field where to write the potential.

wcomp: The component of the write field.

coeff: Diagonal coefficient.

rTFld: The field from which to restore time.

alpha: The multiplying factor when calculating the potential.

linearSolver Macro

linearSolver (name):

Macro for the linear solver block. Uses a gmres solver.

linearSolver Macro Parameters

name: The name of the LinearSolver.

esSolveDirichlet Macro

esSolveDirichlet (NXLO, NYLO, NZLO, NXHI, NYHI, NZHI, srcFld, fld, comp, rstTimeFld, dcoeff, xcoeff,ycoeff, zcoeff, scl):

Macro to solve with 0.0 at the boundary.

144 Chapter 8. Macros

Page 149: VSim In Depth

VSim In Depth, Release 8.2.1

esSolveDirichlet Macro Parameters

NXLO: Lower bound in the x direction (grid cell).

NYLO: Lower bound in the y direction (grid cell).

NZLO: Lower bound in the z direction (grid cell).

NXHI: Upper bound in the x direction (grid cell).

NYHI: Upper bound in the y direction (grid cell).

NZHI: Upper bound in the z direction (grid cell).

srcFld: Source field for the solve.

fld: The field to write the results of the solve to.

comp: The component of the read/write field.

rstTimeFld: The field from which to restore time.

dcoeff: Diagonal coefficient for the laplacian.

xcoeff: X-coefficient for the laplacian.

ycoeff: Y-coefficient for the laplacian.

zcoeff: Z-coefficient for the laplacian.

scl: The scaling applied to all matrix and vector entries for BCs.

esSolveDirichletFromField Macro

esSolveDirichletFromField (NXLO, NYLO, NZLO, NXHI, NYHI, NZHI, srcFld, fld, comp, rstTimeFld,dcoeff, xcoeff, ycoeff, zcoeff, scl):

Macro to solve with boundary conditions set from the result field.

esSolveDirichletFromField Macro Parameters

NXLO: Lower bound in the x direction (grid cell).

NYLO: Lower bound in the y direction (grid cell).

NZLO: Lower bound in the z direction (grid cell).

NXHI: Upper bound in the x direction (grid cell).

NYHI: Upper bound in the y direction (grid cell).

NZHI: Upper bound in the z direction (grid cell).

srcFld: Source field for the solve.

fld: The field to write the results of the solve to.

comp: The component of the read/write field.

rstTimeFld: The field from which to restore time.

dcoeff: Diagonal coefficient for the laplacian.

xcoeff: X-coefficient for the laplacian.

8.2. Macros present in Version 7 145

Page 150: VSim In Depth

VSim In Depth, Release 8.2.1

ycoeff: Y-coefficient for the laplacian.

zcoeff: Z-coefficient for the laplacian.

scl: The scaling applied to all matrix and vector entries for BCs.

8.2.13 Far Fields Macro File

This macro file can be imported to an input file with $ import farFields.

This macro file is available to the VSimEM package.

This macro file enables the calculation of the electromagnetic fields far from the computational domain using Green’sfunctions.

There are two versions of this macro, addFarFields and addFarFieldsGPU. They have the same functionality, howeverthey are meant to be used for simulations run on a CPU and GPU, respectively.

addFarFields ():

This macro defines the fields, updaters and update steps to be able to calculate far fields. It is dependent on macrogenerated multifields, and is incompatible with user generated multifields. The addFarFields macro is located in thefile farFields.mac.

It also is also dependant on the antennas macro, to call a history that will record the far field data. This history is titledaddFarFieldHistory and is located in the file antennas.mac

8.2.14 Filters Macro File

This macro file can be imported to an input file with $ import filters.

This macro file is available to the VSimMD and VSimPA packages.

This macro file provides some useful filters for diagnostic purposes.

filter (elecfield, workingmagfield, boundaryname, maxeigenval, filterval, nxl, nyl, nzl, nxu, nyu, nzu, updatestep):This macro applies an EM noise filter, especially for Numerical Cerenkov

Several filters in sequence can be used. The following are suggested

filterval = 1 ... one stage filter, medium damping, P(x) = 1-x filterval = 1, 1 ... twostage filter, strong damping, P(x) = (1-x)*(1-x) filterval = -1, 1 ... two stage filter,weaker damping, P(x) = (1-x*x) filterval = 1, -2, 1 ... three stage filter, weakerdamping at long wavelengths, strong damping at short wavelengths, P(x) = 1-3*x*x+2*x*x*x

In general, if x = eigenvalue/maxeigenval, then that mode will be damped according to thevalue of the polynomial,(1-filterval_1*x)*(1-filterval_2*x)*with the polynomial shown inthe three examples above.

Example of use:

<Field WorkMagField>numComponents = 3offset = face

</Field>

<UpdateStep NormalAmpereStep1.0>toDtFrac = 1.0updaters = [yeeAmpere]

146 Chapter 8. Macros

Page 151: VSim In Depth

VSim In Depth, Release 8.2.1

messageFields = [YeeElecField]</UpdateStep>

$ MAX_EIGENVAL = SPD_LIGHT*SPD_LIGHT*DT*DT*(1./DX**2 + 1./DY**2)/(CFL_FACTOR*CFL_→˓FACTOR)filter(YeeElecField, WorkMagField, myBoundary, MAX_EIGENVAL, 1.0, 0, 0, 0, NX, NY,→˓NZ, 2.0)filter(YeeElecField, WorkMagField, myBoundary, MAX_EIGENVAL, -2.0, 0, 0, 0, NX, NY,→˓NZ, 2.2)filter(YeeElecField, WorkMagField, myBoundary, MAX_EIGENVAL, 1.0, 0, 0, 0, NX, NY,→˓NZ, 2.4)

<UpdateStep NormalFaradayStep3.0>toDtFrac = 1.0updaters = [yeeFaraday deyMittraFaraday]messageFields = [YeeMagField]

</UpdateStep>

Note that if there are unusual boundary conditions applied to the electric field interior to the domain, they shouldprobably be re-imposed after each filter step. This macro is encrypted and is available with the VSimMD License.

Filter Macro Parameters

elecfield: Name of the dynamic electric field.

workingmagfield: Name of a working magnetic field, e.g, NOT the dynamic magnetic field

boundaryname: Name of the electromagnetic GridBoundary, or 0, if none.

maxeigneval: Maximum Maxwell eigenvalue, e.g., = 4 * c^2 * dt^2 * (1/dx^2 + 1/dy^2 + 1/dz^2) /(dmfrac^2).

filterval: Filter value, e.g., = 1, for a single stage filter, see macro notes for more.

nxl: Lower bound in X.

nyl: Lower bound in Y.

nzl: Lower bound in Z.

nxu: Upper bound in X.

nyu: Upper bound in Y.

nzu: Upper bound in Z.

updatestep: Update step for filter sequence.

8.2.15 Geometry Macro File

This macro file can be imported to an input file with $ import geometry.

This macro file is available to the VSimEM, VSimMD, and VSimPD packages.

This macro file provides some useful functions for creating geometries for simulations. There are two versions ofthis macro, one, geometry, is for use when doing computations on a CPU, the other, geometryGPU, is used forcomputations on a GPU. They retain the exact same functionality, however GPU and CPU macros cannot be mixed.The GPU version only works with the VSimEM package.

8.2. Macros present in Version 7 147

Page 152: VSim In Depth

VSim In Depth, Release 8.2.1

Geometry Macro Introduction

A very powerful tool exists in VSim to create complex shapes for simulation. Simply import the geometry.mac fileand a large number of primitive shapes are available to combine into complex shapes. This file also contains macrosto import .stl and python-defined shapes.

Basic Filling/Voiding

The default way to begin forming geometry is to void the universe and then fill it with shapes one at a time. To ensurea void starting environment use the command, resetGeoToVoid().

Alternatively you can begin forming geometry by filling the entire region with metal and then void shapes, that is,carve out hollow spaces. The filled starting environment is created with resetGeoToFill(universe). Note that a name,in this case universe must be given for a filled environment.

Filling and Voiding operations act on the previously defined operations. This means that the order of shape fillingand voiding is important. This is expanded upon further in Advanced Filling and Voiding and is demonstrated in theridgedWaveguide macro, below.

Grid Boundaries

To finalize the geometry as a grid boundary, the command

saveGeoToGridBoundary(gridBoundaryName,CFL_FACTOR)

must be used. If a reusable complex shape is desired, the shape may be constructed as a macro, with the argument ofthe macro listed as the shape name. An example is given below,

<macro ridgedWaveguide()>voidGeoExpression(waveguideBox,geoBoxP,x,y,z,.5,.4,.15))fillGeoExpression(ridge_1,geoBoxP(x-.25,y ,z,.1,.15,.15))fillGeoExpression(ridge_2,geoBoxP(x-.25,y-.25,z,.1,.15,.15))fillGeoExpression(ridge_3,geoBoxP(x ,y-.25,z,.1,.15,.15))fillGeoExpression(ridge_4,geoBoxP(x ,y ,z,.1,.15,.15))

</macro>ridgedWaveguide()saveGeoToGridBoundary(waveguide,CFL_FACTOR)

There is also a version of this macro that allows the saving of the volumes:

saveGeoToGridBoundary(gridBoundaryName,CFL_FACTOR,calcVol)

An example is

<macro ridgedWaveguide()>voidGeoExpression(waveguideBox,geoBoxP,x,y,z,.5,.4,.15))fillGeoExpression(ridge_1,geoBoxP(x-.25,y ,z,.1,.15,.15))fillGeoExpression(ridge_2,geoBoxP(x-.25,y-.25,z,.1,.15,.15))fillGeoExpression(ridge_3,geoBoxP(x ,y-.25,z,.1,.15,.15))fillGeoExpression(ridge_4,geoBoxP(x ,y ,z,.1,.15,.15))

</macro>ridgedWaveguide()saveGeoToGridBoundary(waveguide,CFL_FACTOR,true)

148 Chapter 8. Macros

Page 153: VSim In Depth

VSim In Depth, Release 8.2.1

Shape Primitives

The geometry macro contains several built in shapes. These are as follows

Fig. 8.2: geoBoxP (x,y,z,LXO,LYO,LZO)

geoBoxP Parameters

LXO: Length of box in X (m).

LXO: Length of box in Y (m).

LXO: Length of box in Z (m).

geoQuadrilateralSlabXP Parameters

LXO: Length of box in X (m).

ya: Y-coordinate of first corner in quadrilateral, measured clockwise (m).

za: Z-coordinate of first corner in quadrilateral, measured clockwise (m).

yb: Y-coordinate of second corner in quadrilateral, measured clockwise (m).

zb: Z-coordinate of second corner in quadrilateral, measured clockwise (m).

yc: Y-coordinate of third corner in quadrilateral, measured clockwise (m).

zc: Z-coordinate of third corner in quadrilateral, measured clockwise (m).

yd: Y-coordinate of fourth corner in quadrilateral, measured clockwise (m).

zd: Z-coordinate of fourth corner in quadrilateral, measured clockwise (m).

8.2. Macros present in Version 7 149

Page 154: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 8.3: geoQuadrilateralSlabXP (x,y,z,LXO,ya,za,yb,zb,yc,zc,yd,zd)

Fig. 8.4: geoTriangleSlabXP (x,y,z,LXO,ya,za,yb,zb,yc,zc)

150 Chapter 8. Macros

Page 155: VSim In Depth

VSim In Depth, Release 8.2.1

geoTriangleSlabXP Parameters

LXO: Length of box in X (m).

ya: Y-coordinate of first corner in triangle, measured clockwise (m).

za: Z-coordinate of first corner in triangle, measured clockwise (m).

yb: Y-coordinate of second corner in triangle, measured clockwise (m).

zb: Z-coordinate of second corner in triangle, measured clockwise (m).

yc: Y-coordinate of third corner in triangle, measured clockwise (m).

zc: Z-coordinate of third corner in triangle, measured clockwise (m).

Fig. 8.5: geoBiParabolicSlabXP (x,y,z,LXO,yVertexIn,yVertexOut,halfHeightZIn,halfHeightZOut)

geoBiParabolicSlabXP Parameters

LXO: Length of biparabolic slab in X (m).

yVertexIn: Y-coordinate of the inner vertex (m).

yVertexOut: Y-coordinate of the outer vertex (m).

halfHeightZIn: Z-coordinate of the inner height(m).

halfHeightZOut: Z-coordinate of the outer height (m).

geoCylinderXP Parameters

RADIUS: Radius of the cylinder (m).

LXO: Length of cylinder in X (axial direction) (m).

8.2. Macros present in Version 7 151

Page 156: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 8.6: geoCylinderXP (x,y,z,RADIUS,LXO)

Fig. 8.7: geoPipeXP (x,y,z,INNER_RADIUS,RADIUS,LXO)

152 Chapter 8. Macros

Page 157: VSim In Depth

VSim In Depth, Release 8.2.1

geoPipeXP Parameters

INNER_RADIUS: Inner radius of the pipe (m).

RADIUS: Outer radius of the pipe (m).

LXO: Length of pipe in X (axial direction) (m).

Fig. 8.8: geoConeXP (x,y,z,MINOR_RADIUS,MAJOR_RADIUS,LXO)

geoConeXP Parameters

INNER_RADIUS: Minor radius of the pipe (m).

MAJOR_RADIUS: Major radius of the cone (m).

LXO: Length of cone in X (axial direction) (m).

Spherical Shape Primitives

geoHemiSphereXP Parameters

RADIUS: Radius of the hemisphere (m).

geoSphereXP Parameters

RADIUS: Radius of the sphere (m).

geoTorusX Parameters

MINOR_RADIUS: Radius of the physical torus (m).

8.2. Macros present in Version 7 153

Page 158: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 8.9: geoHemiSphereXP (x,y,z,RADIUS)

Fig. 8.10: geoSphere (x,y,z,RADIUS)

154 Chapter 8. Macros

Page 159: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 8.11: geoTorusX (x,y,z,MINOR_RADIUS,MAJOR_RADIUS)

MAJOR_RADIUS: Distance between the origin and the middle of the torus (m).

geoRndCylinderXP Parameters

RADIUS: Radius of the cylinder (m).

LXO: Length of the cylinder, axial direction is x by default (m).

RND_RADIUS: Radius of the rounded edge of the cylinder (m).

geoRndRectangleSlabXP Parameters

LXO: Length of box in X (m).

LXO: Length of box in Y (m).

LXO: Length of box in Z (m).

RND_RADIUS: Radius of the rounded edge of the box (m).

geoEllipsoid Parameters

A: Eccentricity of the ellipsoid in X.

B: Eccentricity of the ellipsoid in Y.

C: Eccentricity of the ellipsoid in Z.

8.2. Macros present in Version 7 155

Page 160: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 8.12: geoParaboloidXP (x,y,z,xVertex,RADIUS)

Fig. 8.13: geoRndCylinderXP (x,y,z,RADIUS,LXO,RND_RADIUS)

156 Chapter 8. Macros

Page 161: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 8.14: geoRndRectangleSlabXP (x,y,z,LZO,LYO,LZO,RND_RADIUS)

Fig. 8.15: geoEllipsoid (x,y,z,A,B,C)

8.2. Macros present in Version 7 157

Page 162: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 8.16: geoHemiEllipsoidXP (x,y,z,A,B,C)

geoHemiEllipsoidXP Parameters

A: Eccentricity of the hemiellipsoid in X.

B: Eccentricity of the hemiellipsoid in Y.

C: Eccentricity of the hemiellipsoid in Z.

geoEllipticalCylinderXP Parameters

B: Eccentricity of the elliptical cylinder in Y.

C: Eccentricity of the elliptical cylinder in Z.

LXO: Length of the elliptical cylinder in the X direction.

geoEllipticalConeXP Parameters

B: Eccentricity of the elliptical cone in Y.

C: Eccentricity of the elliptical cone in Z.

lowerScale: Scale of the bottom of the cone.

upperScale: Scale of the top of the cone.

LXO: Length of the elliptical cone in the X direction.

In general, shapes in the geometry macro are created in the Y-Z plane, and then extruded through the X axis. Forexample a cylinder is circular in the Y-Z plane, and has its length in the X direction.

158 Chapter 8. Macros

Page 163: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 8.17: geoEllipticalCylinderXP (x,y,z,B,C,LXO)

Fig. 8.18: geoEllipticalConeXP (x,y,z,B,C,lowerScale,upperScale,LXO)

8.2. Macros present in Version 7 159

Page 164: VSim In Depth

VSim In Depth, Release 8.2.1

Moving Shapes

In general, the primitive shapes place points of rotation symmetry, such as the center of a circle at the origin. Rectilinearshapes begin at the origin and extend in the X-direction.

To move a shape in the X,Y and Z direction, the arguments of the function must be adjusted. For example to move abox 3 meters in the positive X direction the input would be geoBox(x-3,y,z,5,5,5). It would remain 5 meters long inthe X direction. Adding instead of subtracting will cause a shift in the negative X direction.

Rotating Shapes

It is common to need to rotate a shape’s orientation. This is most common in shapes such as cylinders, or tori. Allshapes in the geometry macro have their axial direction in the X axis. To set the Y axis as the axial direction, simplyexchange the variables Y and X. For example geoCylinder(y,x,z,.3,.8)

Fig. 8.19: Default Rotation Cylinder

Advanced Filling and Voiding

By using a sequence of fills and voids, complex shapes can be quickly created and tested. Here we illustrate this withthe ridged waveguide. We start with a filled environment. Next we void out a rectangular waveguide, and then usingfills to create the ridges. This is demonstrated in the example file.

Importing Objects From STL Files

The geometry macro can import CAD generated geometry directly from an STL file. (STEP files may also be convertedto STL through the TXGML setup interface. See setup-win-visual-setup-simulations.) This is handled in the samemanner as creating a rudimentary shape.

voidGeoCad (objectName,stlFileName,shapeComplement,scaling,translation):

160 Chapter 8. Macros

Page 165: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 8.20: Rotated Cylinder

Fig. 8.21: Ridged waveguide made of “fill” and “void” regions

8.2. Macros present in Version 7 161

Page 166: VSim In Depth

VSim In Depth, Release 8.2.1

fillGeoCad (objectName,stlFileName,shapeComplement,scaling,translation):

fillGeoFastCAD (objectName,stlFileName,dmfrac,shapeComplement,scaling):

void/fillGeoCad Macro Parameters

objectName: Name of the geometry object.

stlFileName: Name of the STL file to be imported.

shapeComplement: Binary True or False. Reverses the meaning of inside/outside. Normally set toFalse to insert the shape into the simulation domain. Set to True if you want to import the interior ofthe shape and remove everything exterior to it from your domain.

scaling: Scaling factor to be applied to STL shape. Most commonly used to adjust units of STL fileto meters.

translation: Vector describing any translations applied to STL shape; is defined in terms of the unitsof the STL file.

CAD shapes can be used together with primitive shapes. Note that when using the shapeComplement feature, it isimportant that the .stl file have a single solid, as is the common usage, and that the solid be connected. If there aremore than one disconnected shapes, then multiple .stl files should be used.

fillGeoFastCAD Macro Parameters

New in VSim 7.0, the fillGeoFastCAD macro makes use of the VMesh fast meshing capabilities and is an alternativeto fillGeoCad.

Note: Unlike fillGeoCad or any other geometry declaration, a fillGeoFastCAD macro call ought not be followed upby a saveGeoToGridBoundary call.

objectName: Name of the geometry object.

stlFileName: Name of the STL file to be imported.

dmfrac: Value of Dey-Mittra fraction, see Dey-Mittra Conformal Boundary Algorithm.

shapeComplement: Binary: True or False. Reverses the meaning of inside/outside. Normally set to False to insertthe shape into the simulation domain. Set to True if you want to import the interior of the shape and removeeverything exterior to it from your domain.

scaling: Scaling factor to be applied to the STL shape. Most commonly used to adjust units of STL file to meters.

Importing a Python File

The geometry macro contains the ability to import a python-defined shape into the simulation environment. This isdone with the command shown below.

voidGeoPython (objectName,functionName): fillGeoPython (objectName,functionName):

void/fillGeoPython Macro Parameters

objectName: Name of the geometry object.

162 Chapter 8. Macros

Page 167: VSim In Depth

VSim In Depth, Release 8.2.1

functionName: Name of the function within the python file.

The python file itself must have the same name as the input file name (excluding the file extension), and contain thespecified function. The function should evaluate to unity inside the shape and zero outside the shape.

Shape Primitive Creation

Sometimes it may be desired to create a new shape primitive. This technique is most useful if creating an input filewith a repetitive, complex geometry. The basis of all shape primitives is the Heaviside function.

In the code block given below, the macro hollowSphere specifies a sphere in which the sphere only extends between aspecified inner and outer radius.

Fig. 8.22: hollowSphere (x,y,z,rInner,rOuter)

<macro hollowSphere(x,y,z,rInner,rOuter)>( H(rOuter^2 - x^2 - y^2 - z^2)-H(rInner^2 - x^2 - y^2 - z^2) )

</macro>

Tips/Tricks

When building complex shapes it tends to be easier to initially center the shapes around the origin, and then movethem into place. This way mirroring or rotating a shape around any of the axis is easy and understandable. It is alsorecommended when starting out to create a large domain to create shapes in. This way if an error in the translation orsize is made it is possible that it will still appear in the domain, making the error easier to spot. Increasing the numberof cells helps sharpen corners and smooths rounded shapes.

8.2.16 History Macro File

This macro file can be imported to an input file with $ import history.

8.2. Macros present in Version 7 163

Page 168: VSim In Depth

VSim In Depth, Release 8.2.1

This macro file is available to all packages.

The hist macro file contains many of the histories used in simulations, for a detailed description of each history andhow to call it please see VSim Reference. This macro can be imported to an input file with $ import hist. This macrois unencrypted and is available with a VSimBase license.

saveHistories Macro

saveHistories ():

This macro saves the histories generated via macros.

addFieldAtCoordBlock Macro

This history records the value of a field in the components specified at the point specified. More informa-tion is available at rm-fieldatcoords

addFieldAtCoordHist (name,fieldName,comp,px,py,pz):

name: The name of the history.

fieldName: The name of the field used in the hstory.

comp: Components to be used in the history.

px: X-coordinate of the history.

py: Y-coordinate of the history.

pz: Z-coordinate of the history.

addPoyntingHist Macro

addPoyntingHist (name,elecfield,magfield,lx,ly,lz,ux,uy,uz):

name: The name of the history.

elecfield: The name of the electric field used in the hstory.

magfield: The name of the magnetic field used in the hstory.

lx: Lower X-coordinate of the history.

ly: Lower Y-coordinate of the history.

lz: Lower Z-coordinate of the history.

ux: Upper X-coordinate of the history.

uy: Upper Y-coordinate of the history.

uz: Upper Z-coordinate of the history.

addFieldSqrVolOpHist Macro

addFieldSqrVolOpHist (histName, scope, fieldName, operation, multiplyByDV, recordFieldValue, recordPosi-tion, lbs, ubs,gridName, gridBndry, inside, order, applyStep, multFactor, label):

A macro to add a history that calculates the volume integral of a field-squared within a given volume V, i.e., the integral over V of ||F||^2 dV (times multFactor)N.B. this history may take a relatively long time.

164 Chapter 8. Macros

Page 169: VSim In Depth

VSim In Depth, Release 8.2.1

hisName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”,and the field name can then be qualified with the MultiField or EmField).

fieldName: The name of the field used in the hstory.

operation: sumOverCells, maxOverCells, or minOverCells.

multiplyByDV: Whether to multiply by dV, either 0 or 1 (false or true).

recordFieldValue: (for min or max, not sum): if 1, the first components will be the value ofthe field (with dA if requested, without multFactor) at min/max.

recordPosition: if 1, the coordinates of the min/max field will be added (after field values ifdesired).

lbs: the lower bounds (can be “”, for whole sim domain).

ubs: the upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of the grid boundary, can be “” for no boundary.

inside: if 1, integrate inside gridBndry, if 0, outside.

order: the order of interpolation to use (N.B. this volume integration has second-order error, sousing order > 1 is probably not really useful).

applyStep: the integer time step at which to calculate the history.

multFactor: a factor by which to multiply the field energy.

label: a string-vec label for history file (can be “” for generic label).

addTwoFieldSqrVolOpHist Macro

addTwoFieldSqrVolOpHist (histName, scope, fieldName1, fieldName2, operation, multiplyByDV, record-FieldValue, recordPosition, lbs, ubs,gridName, gridBndry, inside, order, applyStep, multFactor, multFactor2, label):

A macro to add a history that calculates the desired operation (min, max, sum) of a field-squared within a given volumeV, i.e., the integral over V of a(||F||^2 + b||G||^2) dV (where a = multFactor, b = multFactor2, and F and G are the fields)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

fieldName1: The name of the first field used in the hstory.

fieldName2: The name of the second field used in the hstory.

operation: sumOverCells, maxOverCells, or minOverCells.

multiplyByDV: Whether to multiply by dV, either 0 or 1 (false or true).

recordFieldValue: (for min or max, not sum): if 1, the first components will be the value of thefield (with dA if requested, without multFactor) at min/max.

recordPosition: If 1, the coordinates of the min/max field will be added (after field values if de-sired).

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

8.2. Macros present in Version 7 165

Page 170: VSim In Depth

VSim In Depth, Release 8.2.1

gridName: The name of the grid.

gridBndry: The name of the grid boundary, can be “” for no boundary.

inside: If 1, integrate inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this volume integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the field energy.

multFactor2: Second factor by which to multiply the field energy.

label: A string-vec label for history file (can be “” for generic label).

addFieldSqrVolIntegralHist Macro

addFieldSqrVolIntegralHist (histName, scope, fieldName, lbs, ubs, gridName, gridBndry, inside, order,applyStep, multFactor, label):

A macro to add a history that calculates the volume integral of a field-squared within a given volume V, i.e., the integralover V of ||F||^2 dV (times multFactor)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

fieldName: The name of the field used in the hstory.

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of the grid boundary, can be “” for no boundary.

inside: If 1, integrate inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this volume integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the field energy.

label: A string-vec label for history file (can be “” for generic label).

addFieldSqrVolMaxHist Macro

addFieldSqrVolMaxHist (histName, scope, fieldName, recordFieldValue, recordPosition, lbs, ubs, gridName,gridBndry, inside, order, applyStep, multFactor, labels):

A macro to add a history that calculates the volume integral of a field-squared within a given volume V, i.e., the integralover V of ||F||^2 dV (times multFactor)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

fieldName: The name of the field used in the hstory.

166 Chapter 8. Macros

Page 171: VSim In Depth

VSim In Depth, Release 8.2.1

recordFieldValue: (for min or max, not sum): if 1, the first components will be the value of thefield (with dA if requested, without multFactor) at min/max.

recordPosition: If 1, the coordinates of the min/max field will be added (after field values if de-sired).

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of the grid boundary, can be “” for no boundary.

inside: If 1, integrate inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this volume integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the field energy.

label: A string-vec label for history file (can be “” for generic label).

addTwoFieldSqrVolMaxHist Macro

addTwoFieldSqrVolMaxHist (histName, scope, fieldName1, fieldName2, recordFieldValue, recordPosition,lbs, ubs, gridName, gridBndry, inside, order, applyStep, multFactor, multFactor2, labels):

A macro to add a history that calculates the max of the sum of two field-squared within a given volume V, e.g. maxover V of the quantity: a(||F||^2 + b||G||^2) (where a = multFactor, b = multFactor2)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

fieldName1: The name of the first field used in the hstory.

fieldName2: The name of the second field used in the hstory.

recordFieldValue: (for min or max, not sum): if 1, the first components will be the value of thefield (with dA if requested, without multFactor) at min/max.

recordPosition: If 1, the coordinates of the min/max field will be added (after field values if de-sired).

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of the grid boundary, can be “” for no boundary.

inside: If 1, integrate inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this volume integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the field energy.

multFactor2: Second factor by which to multiply the field energy.

8.2. Macros present in Version 7 167

Page 172: VSim In Depth

VSim In Depth, Release 8.2.1

label: A string-vec label for history file (can be “” for generic label).

add2FieldSqrVolIntegralHistMacro

add2FieldSqrVolIntegralHist (histName, scope, fieldName1, fieldName2, lbs, ubs, gridName, gridBndry,inside, order, applyStep, multFactor1, multFactor2 ):

A macro to add a history that calculates the max of the sum of two field-squared within a given volume V, e.g. maxover V of the quantity: a(||F||^2 + b||G||^2) (where a = multFactor, b = multFactor2)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

fieldName1: The name of the field F.

fieldName2: The name of the field G.

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of the grid boundary, can be “” for no boundary.

inside: If 1, integrate inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this volume integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor1: A factor by which to multiply ||F^2||.

multFactor2: A factor by which to multiply ||G^2||.

addVolInnerProd3Hist Macro

addVolInnerProd3Hist (histName, scope, fieldF, fieldG, lbs, ubs, gridName, gridBndry, inside, gridBndry2,inside2, order, applyStep, sMatrixDiags, sMatrixOffDiags multFactor ):

A macro to add a history that calculates the volume inner product two fields (which are 3-vector-valued) i.e., theintegral over V of F.S.G dV (times multFactor) where S is a 3x3 symmetric matrix The volume V is the intersectionof 2 regions, each defined by a gridBoundary

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

fieldF: The name of the field F.

fieldG: The name of the field G.

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of a gridBoundary within (or without) which the energy will be calculated (canbe “” for no gridBndry).

168 Chapter 8. Macros

Page 173: VSim In Depth

VSim In Depth, Release 8.2.1

inside: If 1, integrate inside gridBndry, if 0, outside.

gridBndry2: The name of a gridBoundary within (or without) which the energy will be calculated(can be “” for no gridBndry).

inside2: If 1, integrate inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this volume integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

sMatrixDiags: A list [s11 s22 s33] of the diagonal elements of the sMatrix.

sMatrixOffDiags: A list [s23 s31 s12] of the off-diagonal elements of the (symmetric) sMatrix.

multFactor: A factor by which to multiply the field energy.

addFieldSqrSurfOpHist Macro

addFieldSqrSurfOpHist (histName, scope, fieldName, operation, multiplyByDA, recordFieldValue, recordPo-sition, lbs, ubs, gridName, gridBndry, inside, order, applyStep, multFactor, labels):

A macro to add a history that calculates field-squared over a surface e.g., the integral over A of ||F||^2 dA (timesmultFactor) or the maximum over A of ||F||^2 (times multFactor) or the minimum over A of ||F||^2 (times multFactor)(will always be the last value in the history, if more than that value is requested via recordFieldValue or recordPosition)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

fieldName: The name of the field used in the history.

operation: Either sumOverCells, maxOverCells, or minOverCells.

multiplyByDA: Whether to multiply by dA, either 0 or 1 (false or true).

recordFieldValue: (for min or max, not sum): if 1, the first components will be the components ofthe field (not multiplied by dA or multFactor) at min/max.

recordPosition: (for min or max, not sum): if 1, the coordinates of the min/max field will be added(after field values if desired).

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of a gridBoundary within (or without) which the energy will be calculated (canbe “” for no gridBndry).

inside: If 1, integrate inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this volume integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the field energy.

labels: A string-vec of descriptions of the results for the hdf5 file (can be “”).

8.2. Macros present in Version 7 169

Page 174: VSim In Depth

VSim In Depth, Release 8.2.1

addTwoFieldSqrSurfOpHist Macro

addTwoFieldSqrSurfOpHist (histName, scope, fieldName1, fieldName2 operation, multiplyByDA, record-FieldValue, recordPosition, lbs, ubs, gridName, gridBndry, inside, order, applyStep, multFactor, multFactor2, labels):

A macro to add a history that calculates field-squared over a surface for two fields e.g., the integral over A of ||F||^2 +g ||G||^2 dA (times multFactor) or the maximum over A of ||F||^2 + g ||G||^2 (times multFactor) or the minimum overA of ||F||^2 + g ||G||^2 (times multFactor) where f and g are constants. (this will always be the last value in the history,if more than that value is requested via recordFieldValue or recordPosition)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

fieldName1: The name of the field F.

fieldName2: The name of the field G.

operation: Either sumOverCells, maxOverCells, or minOverCells.

multiplyByDA: Whether to multiply by dA, either 0 or 1 (false or true).

recordFieldValue: (for min or max, not sum): if 1, the first components will be the components ofthe field (not multiplied by dA or multFactor) at min/max.

recordPosition: (for min or max, not sum): if 1, the coordinates of the min/max field will be added(after field values if desired).

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of a gridBoundary within (or without) which the energy will be calculated (canbe “” for no gridBndry).

inside: If 1, integrate inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this volume integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the surface integral.

multFactor2: A factor by which to multiply G.

labels: A string-vec of descriptions of the results for the hdf5 file (can be “”).

addFieldSqrSurfIntegralHist Macro

addFieldSqrSurfIntegralHist (histName, scope, fieldName, lbs, ubs, gridName, gridBndry, inside, order,applyStep, multFactor, label):

A macro to add a history that calculates the maximum or minimum of a field-magnitude-squared the maximum orminimum over a surface A of ||F||^2 (times multFactor).

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

fieldName: The name of the field.

170 Chapter 8. Macros

Page 175: VSim In Depth

VSim In Depth, Release 8.2.1

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of a gridBoundary within (or without) which the energy will be calculated (canbe “” for no gridBndry).

inside: If 1, integrate inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this volume integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the surface integral.

labels: A string-vec of descriptions of the results for the hdf5 file (can be “”).

addFieldSqrSurfMaxHist Macro

addFieldSqrSurfMaxHist (histName, scope, fieldName, recordFieldValue, recordPosition, lbs, ubs, gridName,gridBndry, inside, order, applyStep, multFactor, labels):

A macro to add a history that calculates the maximum or minimum of a field-magnitude-squared the maximum orminimum over a surface A of ||F||^2 (times multFactor).

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

fieldName: The name of the field.

recordFieldValue: (for min or max, not sum): if 1, the first components will be the components ofthe field (not multiplied by dA or multFactor) at min/max.

recordPosition: (for min or max, not sum): if 1, the coordinates of the min/max field will be added(after field values if desired).

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of a gridBoundary within (or without) which the energy will be calculated (canbe “” for no gridBndry).

inside: If 1, integrate inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this volume integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the surface integral.

labels: A string-vec of descriptions of the results for the hdf5 file (can be “”).

8.2. Macros present in Version 7 171

Page 176: VSim In Depth

VSim In Depth, Release 8.2.1

addTwoFieldSqrSurfMaxHist Macro

addTwoFieldSqrSurfMaxHist (histName, scope, fieldName1, fieldName2, recordFieldValue, recordPosition,lbs, ubs, gridName, gridBndry, inside, order, applyStep, multFactor, multFactor2, labels):

A macro to add a history that calculates the maximum of two fields squared (times multFactor) over a surface: i.e., of(multFactor) * ( ||F||^2 + g ||G||^2 ) where g is a constant, and dA is optional.

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

fieldName1: The name of the field F.

fieldName2: The name of the field G.

recordFieldValue: (for min or max, not sum): if 1, the first components will be the components ofthe field (not multiplied by dA or multFactor) at min/max.

recordPosition: (for min or max, not sum): if 1, the coordinates of the min/max field will be added(after field values if desired).

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of a gridBoundary within (or without) which the energy will be calculated (canbe “” for no gridBndry).

inside: If 1, integrate inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this volume integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the result.

multFactor: A factor by which to multiply the second field.

labels: A string-vec of descriptions of the results for the hdf5 file (can be “”).

addFieldSqrSurfMinHist Macro

addFieldSqrSurfMinHist (histName, scope, fieldName, recordFieldValue, recordPosition, lbs, ubs, gridName,gridBndry, inside, order, applyStep, multFactor, labels):

A macro to add a history that calculates the minimum of a field-squared (times multFactor) over a surfaceN.B. Thisdoesn’t work unless the minimum value is below 3e38.

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

fieldName: The name of the field.

recordFieldValue: (for min or max, not sum): if 1, the first components will be the components ofthe field (not multiplied by dA or multFactor) at min/max.

recordPosition: (for min or max, not sum): if 1, the coordinates of the min/max field will be added(after field values if desired).

172 Chapter 8. Macros

Page 177: VSim In Depth

VSim In Depth, Release 8.2.1

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of a gridBoundary within (or without) which the energy will be calculated (canbe “” for no gridBndry).

inside: If 1, integrate inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this volume integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the result.

labels: A string-vec of descriptions of the results for the hdf5 file (can be “”).

addFieldSurfComplex3DCrossIntegralHist Macro

addFieldSurfComplex3DCrossIntegralHist (histName, scope, field1Re,field1Im, field2Re, field2Im, lbs,ubs, gridName, gridBndry, inside, order, applyStep, multFactor):

A macro to add a history that calculates the surface-flux integral of a complex field cross product over a surface i.e.,0.5 * integral over A of Re[F1^* x F2].n dA (times multFactor) where F1 and F2 are 3-vector-valued fields and wheren is always the outward unit normal (regardless of whether the region inside or outside of the GridBndry is used). Theprefactor of 1/2 is so the answer reflects the time-average of the integral over A of (Re[F1 exp(-i w t)]xRe[F2 exp(-i wt)]).n dA

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

field1Re: The name of the real part of field F1.

field1Im: The name of the imaginary part of field F1.

field2Re: The name of the real part of field F2.

field2Im: The name of the imaginary part of field F2.

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of a gridBoundary within (or without) which the energy will be calculated (canbe “” for no gridBndry).

inside: If 1, integrate inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this volume integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the result.

8.2. Macros present in Version 7 173

Page 178: VSim In Depth

VSim In Depth, Release 8.2.1

addVoltageGainInOscElecFieldHistBase Macro

addVoltageGainInOscElecFieldHistBase (histName, scope, eField,freq, freqIndex, speed, initialPhase,lbs, ubs, gridCurve, order, applyStep, multFactor):

A macro to add a history that calculates the voltage gained by a charged particle following a curve at constant speed in an oscillating field with given magnitude,i.e., the line integral over the curve of ds.E(x) exp(-2 pi i freq (s(x)/speed) - i initialPhase) (times multFactor)where E is the electric field at point x (on the curve), s(x) is the length (along the curve) from the beginningof the curve to point x, and f is the field’s oscillation frequency speed is the particle’s speed along the curveinitialPhase is the phase of the (complex oscillating) field when the particles starts along the curve i.e., thehistory returns the real and imaginary part of the above, so that if initialPhase = 0, then the real part representsthe voltage gain by a particle that starts along the curve when the given field is at its maximum, and theimaginary part represents the voltage gain by a particle that starts along the curve when the given field is zeroand decreasing (if freq is positive...if freq is negative, then because of the minus sign in exp(-...), it’s as if thefield is increasing from zero). (if multFactor is 1., the result is in Volts)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”,and the field name can then be qualified with the MultiField or EmField).

eField: The name of the e-field.

freq: The oscillation frequency (not angular frequency) of the e-field or the name of a history thatcalculates the frequency (in the latter case, that history must come before this macro is called inthe input file).

freqIndex: If param freq is simply a number, this should be -1;if param freq is the name of ahistory that calculates the frequency, this should be the index (e.g., [0] or [1 2]) of the frequencywithin the history data.

speed: The speed of a charged particle following the curve.

initialPhase: The initial phase (in radians) of the (complex, oscillating) field when the particlestarts along the curve.

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridCurve: The name of a GridCurve along which the field will be integrated.

order: The order of interpolation to use (N.B. this method of integration has second-order error,so using order > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the result.

addVoltageGainInOscElecFieldHist Macro

addVoltageGainInOscElecFieldHist (histName, scope, eField, freq, speed, initialPhase, lbs, ubs, grid-Curve, order, applyStep, multFactor):

A macro to add a history that calculates the voltage gained by a charged particle following a curve at constant speed in an oscillating field with given magnitude, (with given oscillation frequency)

i.e., the line integral over the curve of ds.E(x) exp(-2 pi i freq (s(x)/speed) - i initialPhase) (times multFactor)where E is the electric field at point x (on the curve), s(x) is the length (along the curve) from the beginningof the curve to point x, and f is the field’s oscillation frequency speed is the particle’s speed along the curveinitialPhase is the phase of the (complex oscillating) field when the particles starts along the curve

174 Chapter 8. Macros

Page 179: VSim In Depth

VSim In Depth, Release 8.2.1

i.e., the history returns the real and imaginary part of the above,

so that if initialPhase = 0, then the real part represents the voltage gain by a particle that startsalong the curve when the given field is at its maximum, and the imaginary part represents thevoltage gain by a particle that starts along the curve when the given field is zero and decreasing(if freq is positive...if freq is negative, then because of the minus sign in exp(-...), it’s as if thefield is increasing from zero). (if multFactor is 1., the result is in Volts)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

eField: The name of the e-field.

initialPhase: The initial phase (in radians) of the (complex, oscillating) field when the particle startsalong the curve.

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridCurve: The name of a GridCurve along which the field will be integrated.

order: The order of interpolation to use (N.B. this method of integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the result.

addVoltageGainInOscElecFieldHist Macro

addVoltageGainInOscElecFieldHist (histName, scope, eField, freq, speed, initialPhase, lbs, ubs, grid-Curve, order, applyStep, multFactor):

A macro to add a history that calculates the voltage gained by a charged particle following a curve at constant speed in an oscillating field with given magnitude,(with oscillation frequency given by another History)

i.e., the line integral over the curve of ds.E(x) exp(-2 pi i freq (s(x)/speed) - i initialPhase) (times multFactor)where E is the electric field at point x (on the curve), s(x) is the length (along the curve) from the beginningof the curve to point x, and f is the field’s oscillation frequency speed is the particle’s speed along the curveinitialPhase is the phase of the (complex oscillating) field when the particles starts along the curve

i.e., the history returns the real and imaginary part of the above, so that if initialPhase = 0, then the realpart represents the voltage gain by a particle that starts along the curve when the given field is at itsmaximum, and the imaginary part represents the voltage gain by a particle that starts along the curve whenthe given field is zero and decreasing (if freq is positive...if freq is negative, then because of the minus signin exp(-...), it’s as if the field is increasing from zero). (if multFactor is 1., the result is in Volts)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and the fieldname can then be qualified with the MultiField or EmField).

eField: The name of the e-field.

freq: The oscillation frequency (not angular frequency) of the e-field or the name of a history that calculatesthe frequency (in the latter case, that history must come before this macro is called in the input file).

speed: The speed of a charged particle following the curve.

8.2. Macros present in Version 7 175

Page 180: VSim In Depth

VSim In Depth, Release 8.2.1

initialPhase: The initial phase (in radians) of the (complex, oscillating) field when the particle starts alongthe curve.

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridCurve: The name of a GridCurve along which the field will be integrated.

order: The order of interpolation to use (N.B. this method of integration has second-order error, so usingorder > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the result.

addEnergyInBHist Macro

addEnergyInBHist (histName, scope, bField, lbs, ubs, gridName, gridBndry, inside, order, applyStep, multFac-tor):

A macro to add a history that calculates the energy in the magnetic (B) field within a given volume V, i.e., the integralover V of ||B||^2/(2 mu_0) dV (if multFactor is 1., the result is the magnetic field energy in Joules, although in 2D youit’s really Joules/m, and in 1D, Joules/m^2)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

bField: The name of the b-field.

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridBndry: The name of a gridBoundary within (or without) which the energy will be calculated (canbe “” for no gridBndry).

inside: If 1, calculate energy inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this method of integration has second-order error, sousing order > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the result.

addEnergyInBHistComplex Macro

addEnergyInBHistComplex (histName, scope, Breal, Bimag, lbs, ubs, gridName, gridBndry, inside, order,applyStep, multFactor):

A macro to add a history that calculates the energy in the complex magnetic (B) field within a given volume V, i.e.,(1/2) the integral over V of ||B||^2/(2 mu_0) dV (if multFactor is 1., the result has units of Joules, although in 2D youit’s really Joules/m, and in 1D, Joules/m^2). The prefactor (1/2) reflects the time-average of the integral over V ofRe[B exp(-i w t)]^2/(2 mu_0) dV

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

176 Chapter 8. Macros

Page 181: VSim In Depth

VSim In Depth, Release 8.2.1

Bimag: The imaginary part of the b-field.

Breal: The real part of the b-field.

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of a gridBoundary within (or without) which the energy will be calculated (canbe “” for no gridBndry).

inside: If 1, calculate energy inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this method of integration has second-order error, sousing order > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the result.

addEnergyInEHist Macro

addEnergyInEHist (histName, scope, eField, lbs, ubs, gridName, gridBndry, inside, order, applyStep, multFac-tor):

A macro to add a history that calculates the energy in the electric (E) field within a given volume V, i.e., the integralover V of ||B||^2/(2 mu_0) dV (if multFactor is 1., the result is the magnetic field energy in Joules, although in 2D youit’s really Joules/m, and in 1D, Joules/m^2)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

eField: The name of the e-field.

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridBndry: The name of a gridBoundary within (or without) which the energy will be calculated (canbe “” for no gridBndry).

inside: If 1, calculate energy inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this method of integration has second-order error, sousing order > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the result.

addEnergyInEHistComplex Macro

addEnergyInEHistComplex (histName, scope, Ereal, Eimag, lbs, ubs, gridName, gridBndry, inside, order, ap-plyStep, multFactor):

A macro to add a history that calculates the energy in the complex electric (E) field within a given volume V, i.e., (1/2)the integral over V of ||B||^2/(2 mu_0) dV (if multFactor is 1., the result has units of Joules, although in 2D you it’sreally Joules/m, and in 1D, Joules/m^2). The prefactor (1/2) reflects the time-average of the integral over V of Re[Bexp(-i w t)]^2/(2 mu_0) dV

8.2. Macros present in Version 7 177

Page 182: VSim In Depth

VSim In Depth, Release 8.2.1

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

Eimag: The imaginary part of the e-field.

Ereal: The real part of the e-field.

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of a gridBoundary within (or without) which the energy will be calculated (canbe “” for no gridBndry).

inside: If 1, calculate energy inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this method of integration has second-order error, sousing order > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the result.

addEnergyInDielectricFromEHist Macro

addEnergyInDielectricFromEHist (histName, scope, fieldName, lbs, ubs, gridName, dielGridBndry, in-sideDiel, volumeGridBndry, insideVolume, order, applyStep, epsilonDiags, epsilonOffDiags, multFactor):

A macro to add a history that calculates the energy in the electric (E) field within a region of uniform dielectric in agiven volume V, i.e., the integral over intersection(V, diel. region) of D.E/2 dV (if multFactor is 1., the result has unitsof Joules, although in 2D you it’s really Joules/m, and in 1D, Joules/m^2)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

dielGridBndry: The name of a gridBoundary that describes a region within (or without) which isuniform dielectric–a region in which the energy will be calculated (can be “” for no gridBndry).

insideDiel: If 1, calculate energy inside dielGridBndry, if 0, outside.

volumeGridBndry: The name of a gridBoundary within (or without) which the energy will be calcu-lated – this has nothing to with dielectric, just a way to say: calculate the energy within volume V(volumeGridBndry) within the dielectric; the volumeGridBndry should not intersect the dielGridB-ndry/ (the surfaces should not even cut through the same cell)

insideVolume: If 1, calculate energy inside volumeGridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this method of integration has second-order error, sousing order > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

178 Chapter 8. Macros

Page 183: VSim In Depth

VSim In Depth, Release 8.2.1

epsilonDiags: A list [eps_xx eps_yy eps_zz] of the diagonal elements of the relative epsilon matrix(e.g., [1 1 1] in vacuum).

epsilonOffDiags: A list [eps_yz eps_zx eps_xy] of the off-diagonal elements of the (symmetric)relative epsilon matrix (e.g., [0 0 0] in vacuum, or any isotropic dielectric)

multFactor: A factor by which to multiply the result.

addInstantWallDissipationHist Macro

addInstantWallDissipationHist (histName, scope, fieldName, lbs, ubs, gridName, gridBndry, inside, or-der, applyStep, R_S, multFactor, label):

A macro to add a history that calculates the instantaneous energy dissipation (power) in the metal wall containinggiven an RF magnetic field (B). i.e., the integral over A of R_s ||B/mu_0||^2 dA It is assumed that the B-field conformsto the metallic boundary conditions...if not, it may be better to add ‘boundaryCondition = magneticAtPEC’ to the<SpaceFunc B> block. (if multFactor is dimensionless, the result has units of Watts, although in 2D it’s really W/m,and in 1D, W/m^2)

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of a gridBoundary describing the metal wall.

inside: If 1, calculate energy inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this method of integration has second-order error, sousing order > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

R_S: The surface resistance of the metal (in Ohms)–this should be found from experiment (it depends onfrequency), but in naive theory, R_S = rho / delta where rho is the metal’s bulk resistivity, and deltais the skin depth at the frequency in question.

multFactor: A factor by which to multiply the result.

label: A description of the result for the hdf5 file; can be set to “defaultLabel” for default label.

addTimeAvgWallDissipationHist Macro

addInstantWallDissipationHist (histName, scope, fieldName, lbs, ubs, gridName, gridBndry, inside, or-der, applyStep, R_S, multFactor, label):

A macro to add a history that calculates the time-averaged energy dissipation (power) in the metal wall containing givenan RF magnetic field oscillation amplitude (B). i.e., the integral over A of (1/2) R_s ||B/mu_0||^2 dA It is assumedthat the B-field conforms to the metallic boundary conditions...if not, it may be better to add ‘boundaryCondition =magneticAtPEC’ to the <SpaceFunc B> block. (if multFactor is 1., the result has units of Watts.

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

8.2. Macros present in Version 7 179

Page 184: VSim In Depth

VSim In Depth, Release 8.2.1

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of a gridBoundary describing the metal wall.

inside: If 1, calculate energy inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this method of integration has second-order error, sousing order > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

R_S: The surface resistance of the metal (in Ohms)–this should be found from experiment (it depends onfrequency), but in naive theory, R_S = rho / delta where rho is the metal’s bulk resistivity, and deltais the skin depth at the frequency in question.

multFactor: A factor by which to multiply the result.

label: A description of the result for the hdf5 file; can be set to “defaultLabel” for default label.

addComplexPoyntingSurfaceIntegralHist Macro

addComplexPoyntingSurfaceIntegralHist (histName, scope, Er, Ei, Br, Bi, lbs, ubs, gridName, gridB-ndry, inside, order, applyStep, multFactor):

A macro to add a history that calculates the Poynting-flux integral of complex EM fields over a surface i.e., 1/mu_0times 1/2 integral over A of (E^* x B).n dA (times multFactor) (the 1/2 is so the result yields the time average powercrossing the surface) where E and B are the electric and magnetic fields and where n is always the outward unit normal(regardless of whether the region inside or outside of the GridBndry is used) where the surface A is described by theGridBndry

histName: The name of the history.

scope: The name of the MultiField or EmField containing the field (can be the empty string “”, and thefield name can then be qualified with the MultiField or EmField).

Er: The real part of the e-field

Ei: The imaginary part of the e-field.

Br: The real part of the b-field.

Bi: The imaginary part of the b-field.

lbs: The lower bounds (can be “”, for whole sim domain).

ubs: The upper bounds (can be “”, for whole sim domain).

gridName: The name of the grid.

gridBndry: The name of a gridBoundary describing the metal wall.

inside: If 1, calculate energy inside gridBndry, if 0, outside.

order: The order of interpolation to use (N.B. this method of integration has second-order error, sousing order > 1 is probably not really useful).

applyStep: The integer time step at which to calculate the history.

multFactor: A factor by which to multiply the result.

180 Chapter 8. Macros

Page 185: VSim In Depth

VSim In Depth, Release 8.2.1

8.2.17 initBeam Macro File

This macro file can be imported to an input file with $ import initBeam.

This macro file is available to all packages, but is most useful for VSimPA cases.

This macro file can be used to initialized the electomagnetic fields of a beam initialized inside the simulation window.A static Poisson solve is performed in the frame of the electron beam, the E and B fields are transformed back in thelaboratory frame and set up on the grid.

initBeam Macro

initBeam (density, elecField, magField, gammav, xlo, ylo, zlo, xhi, yhi, zhi, dx, dy, dz, ndim, dumpFields):Define the fields, updaters and initial update steps initializing the electric and magnetic field of a chargedparticle beam on the grid, using Dirichlet boundary conditions.

initBeamWithOpenBdry (density, elecField, magField, gammav, xlo, ylo, zlo, xhi, yhi, zhi, dx, dy, dz, ndim, dumpFields):Define the fields, updaters and initial update steps initializing the electric and magnetic field of a chargedparticle beam on the grid, using open boundary conditions.

initBeam Macro Parameters

density: Charge density of the beam (located at the nodes).

elecField: Resulting electric field (beam self-field, located at the edges).

magField: Resulting magnetic field (beam self-field, located on the face).

gammav: Lorentz factor (gamma) of the charged particle beam in its direction of propagation. gammavis used to do the Lorentz transformation in the beam frame.

nz: Number of cells in the Z-direction.

xlo: Lower boundary cell in x to solve for the fields.

ylo: Lower boundary cell in y to solve for the fields.

zlo: Lower boundary cell in z to solve for the fields.

xhi: Upper boundary cell in x to solve for the fields.

yhi: Upper boundary cell in y to solve for the fields.

zhi: Upper boundary cell in z to solve for the fields.

dx: Grid size in the x direction.

dy: Grid size in the y direction.

dz: Grid size in the z direction.

ndim: Dimension of the simulation.

dumpFields: Whether to dump the intermediary fields used to calculate the beam self-fields. If set to0, those fields will not be dumped.

Example of initBeam Macro

8.2. Macros present in Version 7 181

Page 186: VSim In Depth

VSim In Depth, Release 8.2.1

<MultiField emField># field used to deposit the charge density of the charged particle beam# located at the nodes<Field rhoBeam>

numComponents = 1offset = nonekind = depField

</Field>

# Electric field on edges<Field edgeE>

numComponents = 3offset = edgeinterpolation = esirk2ndOrder

</Field>

# Magnetic field on faces<Field faceB>

numComponents = 3offset = faceinterpolation = esirk2ndOrder

</Field>

initBeam(rhoBeam, edgeE, faceB, BEAM_GAMMA, 0, 0, 0, NX, NY, NZ, DX, DY, DZ, NDIM,→˓0)

</MultiField>

8.2.18 MAL Macro File

This macro file can be imported to an input file with $ import mal.

This macro file is available to all packages.

This set of macros applies a MAL in the slab specified. A matched absorbing layer uses isotropic electric and magneticdamping profiles to absorb the inicident wave. This is unlike a PML (Perfectly Matched Layer) which uses the sameelectric and magnetic damping profiles, but is anisotropic. MAL boundaries are more stable as an anisotropic boundarycondition can beconme unstable when the incident wave has a non-zero imaginary part to its normal wavenumber (e.g.,fringing fields from nearby structure, or particles entering the layer)

This set of macros consists of 5 macros, all of which accept nearly the same exact arguments.

There are two versions of this macro, one, mal, is for use when doing computations on a CPU, the other, malGPU, isused for computations on a GPU. They retain the exact same functionality, however GPU and CPU macros cannot bemixed.

MALprofileDump Macro

MALprofileDump (malName,nxl,nyl,nzl,nxu,nyu,nzu,maldir,malsign,startval,delta,frac,pwr):

This macro is useful for debugging purposes, as it gives the MAL profile.

MALprofileDump Macro Parameters

malName: Name of the MAL layer.

182 Chapter 8. Macros

Page 187: VSim In Depth

VSim In Depth, Release 8.2.1

nxl: Lower bound in the x direction.

nyl: Lower bound in the y direction.

nzl: Lower bound in the z direction.

nxu: Upper bound in the x direction.

nyu: Upper bound in the y direction.

nzu: Upper bound in the z direction.

maldir: 0, 1, or 2 for the x, y, or z direction of the MAL.

malsign: The sign of the outgoing direction.

startval: Any offset of the grid start position in the direction of the MAL (XSTART, YSTART, ZS-TART).

delta: The grid size in the MAL direction.

frac: The peak damping amplitude: 0.5 is suggested, typical range is 0.125 to 2.0.

pwr: The damping profile goes as x**pwer: 3.0 is suggested, typical range is 1.0 to 4.0.

MALdampB_beforeFaraday Macro

MALdampB_beforeFaraday (bField,malName,nxl,nyl,nzl,nxu,nyu,nzu,maldir,malsign,startval,delta,frac,pwr):

This macro must be called in the update step order before the first Faraday update step.

MALdampB_beforeFaraday Macro Parameters

bField: Name of the magnetic field.

malName: Name of the MAL layer.

nxl: Lower bound in the x direction.

nyl: Lower bound in the y direction.

nzl: Lower bound in the z direction.

nxu: Upper bound in the x direction.

nyu: Upper bound in the y direction.

nzu: Upper bound in the z direction.

maldir: 0, 1, or 2 for the x, y, or z direction of the MAL.

malsign: The sign of the outgoing direction.

startval: Any offset of the grid start position in the direction of the MAL (XSTART, YSTART, ZS-TART).

delta: The grid size in the MAL direction.

frac: The peak damping amplitude: 0.5 is suggested, typical range is 0.125 to 2.0.

pwr: The damping profile goes as x**pwer: 3.0 is suggested, typical range is 1.0 to 4.0.

8.2. Macros present in Version 7 183

Page 188: VSim In Depth

VSim In Depth, Release 8.2.1

MALdampE_beforeAmpere Macro

MALdampE_beforeAmpere (eField,malName,nxl,nyl,nzl,nxu,nyu,nzu,maldir,malsign,startval,delta,frac,pwr):

This macro must be called in the update step order before the Ampere update step.

MALdampE_beforeAmpere Macro Parameters

eField: Name of the electric field.

malName: Name of the MAL layer.

nxl: Lower bound in the x direction.

nyl: Lower bound in the y direction.

nzl: Lower bound in the z direction.

nxu: Upper bound in the x direction.

nyu: Upper bound in the y direction.

nzu: Upper bound in the z direction.

maldir: 0, 1, or 2 for the x, y, or z direction of the MAL.

malsign: The sign of the outgoing direction.

startval: Any offset of the grid start position in the direction of the MAL (XSTART, YSTART, ZS-TART).

delta: The grid size in the MAL direction.

frac: The peak damping amplitude: 0.5 is suggested, typical range is 0.125 to 2.0.

pwr: The damping profile goes as x**pwer: 3.0 is suggested, typical range is 1.0 to 4.0.

MALdampE_afterAmpere Macro

MALdampE_afterAmpere (eField,malName,nxl,nyl,nzl,nxu,nyu,nzu,maldir,malsign,startval,delta,frac,pwr):

This macro must be called in the update step order after the Ampere update step.

MALdampE_afterAmpere Macro Parameters

eField: Name of the electric field.

malName: Name of the MAL layer.

nxl: Lower bound in the x direction.

nyl: Lower bound in the y direction.

nzl: Lower bound in the z direction.

nxu: Upper bound in the x direction.

nyu: Upper bound in the y direction.

nzu: Upper bound in the z direction.

maldir: 0, 1, or 2 for the x, y, or z direction of the MAL.

184 Chapter 8. Macros

Page 189: VSim In Depth

VSim In Depth, Release 8.2.1

malsign: The sign of the outgoing direction.

startval: Any offset of the grid start position in the direction of the MAL (XSTART, YSTART, ZS-TART).

delta: The grid size in the MAL direction.

frac: The peak damping amplitude: 0.5 is suggested, typical range is 0.125 to 2.0.

pwr: The damping profile goes as x**pwer: 3.0 is suggested, typical range is 1.0 to 4.0.

MALdampB_afterFaraday Macro

MALdampB_afterFaraday (bField,malName,nxl,nyl,nzl,nxu,nyu,nzu,maldir,malsign,startval,delta,frac,pwr):

This macro must be called in the update step order after the second Faraday update step.

MALdampB_afterFaraday Macro Parameters

bField: Name of the magnetic field.

malName: Name of the MAL layer.

nxl: Lower bound in the x direction.

nyl: Lower bound in the y direction.

nzl: Lower bound in the z direction.

nxu: Upper bound in the x direction.

nyu: Upper bound in the y direction.

nzu: Upper bound in the z direction.

maldir: 0, 1, or 2 for the x, y, or z direction of the MAL.

malsign: The sign of the outgoing direction.

startval: Any offset of the grid start position in the direction of the MAL (XSTART, YSTART, ZS-TART).

delta: The grid size in the MAL direction.

frac: The peak damping amplitude: 0.5 is suggested, typical range is 0.125 to 2.0.

pwr: The damping profile goes as x**pwer: 3.0 is suggested, typical range is 1.0 to 4.0.

8.2.19 Mathphys Macro File

This macro file can be imported to an input file with $ import mathphys.

This macro file is available to all packages.

In many of the input file examples that are supplied in VSimComposer, you will see macros from mathphys invoked.Macros available in mathphys define a series of physical and mathematical constants that are commonly used insimulations. Refer to the mathphys file under Macros in VSimComposer to see which constants are available.

8.2. Macros present in Version 7 185

Page 190: VSim In Depth

VSim In Depth, Release 8.2.1

8.2.20 Matrix Macro File

This macro file can be imported to an input file with $ import matrix.

This macro file is available to all packages.

Provide a set of routines for creating matrices. These are relatively low-level methods for constructing matrices.

Stencil Element Macro

StencilElementMacro (name, value, minDim, offset, rowFldIndx, colFldIndx):

Macro to insert a constant-value matrix StencilElement.

StencilElementMacro Macro Parameters

name: The name to give the stencil element.

value: The value of the stencil element.

minDim: The minimum dimensionality to apply this stencil element.

offset: The offset (in index space) of the column cell from the row cell.

rowFldIndx: The index in the matrix for the row. This corresponds to the writefield for multiply, tothe readfield for solve.

colFldIndx: The index in the matrix for the column. This corresponds to the readfield for multiply,to the writefield for solve.

STFunc Stencil Element Macro

STFuncStencilElementMacro (name, value, minDim, celloffset, funcOffset,rowFldIndx, colFldIndx): Amacro to insert a constant-value matrix StencilElement

STFuncStencilElementMacro Macro Parameters

name: The name to give the stencil element.

value: The value of the stencil element.

minDim: The minimum dimensionality to apply this stencil element.

celloffset: The offset (in index space) of the column cell from the row cell.

funcOffset: The offset (in real space, as a multiple of the grid spacing) of the function evaluationpoint from the row cell.

rowFldIndx: The index in the matrix for the row. This corresponds to the writefield for multiply, tothe readfield for solve.

colFldIndx: The index in the matrix for the column. This corresponds to the readfield for multiply,to the writefield for solve.

186 Chapter 8. Macros

Page 191: VSim In Depth

VSim In Depth, Release 8.2.1

Coord Prod STFunc Stencil Element Macro

CoordProdSTFuncStencilElementMacro (name, value, minDim, cellOffset, funcOffset, gridDir, gridOffset,rowFldIndx, colFldIndx):

A macro to insert a constant-value matrix StencilElement

CoordProdSTFuncStencilElementMacro Macro Parameters

name: The name to give the stencil element.

value: The value of the stencil element.

minDim: The minimum dimensionality to apply this stencil element.

celloffset: The offset (in index space) of the column cell from the row cell.

funcOffset: The offset (in real space, as a multiple of the grid spacing) of the function evaluationpoint from the row cell.

gridDir: The direction in which differencing is being done for the stencil. Determines which gridspacing and face area to use.

gridOffset: The offset (in index space) from the row cell at which the grid spacing and face area aretaken.

rowFldIndx: The index in the matrix for the row. This corresponds to the writefield for multiply, tothe readfield for solve.

colFldIndx: The index in the matrix for the column. This corresponds to the readfield for multiply,to the writefield for solve.

8.2.21 Mirrors Macro File

This macro file can be imported to an input file with $ import mirrors.

This macro file is encrypted and available with a VSimEM or VSimMD license.

MirrorAfterFaradaySetMagFieldToZero Macro

MirrorAfterFaradaySetMagFieldToZero (IXBGN,IYBGN,IZBGN,IXEND,IYEND,IZEND,BFIELD,DTFRACTION):

This macro implements a mirror in the specified region for simulations without particles It wouldbe inserted after each faraday step.

MirrorAfterFaradaySetMagFieldToZero Macro Parameters

IXBGN: Beginning of the mirror in the X direction.

IYBGN: Beginning of the mirror in the Y direction.

IZBGN: Beginning of the mirror in the Z direction.

IXEND: End of the mirror in the X direction.

IYEND: End of the mirror in the Y direction.

IZEND: End of the mirror in the Z direction.

8.2. Macros present in Version 7 187

Page 192: VSim In Depth

VSim In Depth, Release 8.2.1

BFIELD: Face magnetic field

DTFRACTION: DtFrac, typically .5 or 1.0

MirrorAfterFaradaySetCurrentDensToZero Macro

MirrorAfterFaradaySetCurrentDensToZero (IXBGN,IYBGN,IZBGN,IXEND,IYEND,IZEND,CURRENTDENS,BFIELD,DTFRACTION):

This macro implements a mirror in the specified region for simulations with particles. It would be inserted after eachfaraday step after calling the MirrorAfterFaradaySetMagFieldToZero macro.

MirrorAfterFaradaySetCurrentDensToZero Macro Parameters

IXBGN: Beginning of the mirror in the X direction.

IYBGN: Beginning of the mirror in the Y direction.

IZBGN: Beginning of the mirror in the Z direction.

IXEND: End of the mirror in the X direction.

IYEND: End of the mirror in the Y direction.

IZEND: End of the mirror in the Z direction.

CURRENTDENS: Face current density

BFIELD: Face magnetic field

DTFRACTION: DtFrac, typically .5 or 1.0

8.2.22 New Crank-Nicholson Update Matrix Macro File

This macro file can be imported to an input file with $ import ncnmac.

This macro file is available to all packages.

This macro file is used for using the Crank-Nicholson implicit solve for advancing the electromagnetic fields. It is anupdate to the cnmacro macro.

ncnMatrix Macro

ncnMatrix (name, sign): Uses the ∇2 operator. This has the standard problem for implict updates of hyperbolicsystems. Namely, that the operator becomes singular for very implicit times and so takes long to converge

ncnMatrix Macro Parameters

name: The name of the matrix.

sign: Sign (1) for the explicit or application part, (-1) for for the implicit or solve part.

188 Chapter 8. Macros

Page 193: VSim In Depth

VSim In Depth, Release 8.2.1

ncnEpetraUpdater Macro

ncnEpetraUpdaters ():

Defines the explicit and implicit updaters for Crank-Nicholson EM. This macro takes no parameters

cnEmFieldAlgorithm Macro

cnEmFieldAlgorithm (withNodalFields): This macros inserts the Crank-Nicholson update. It assumes thatedgeElec and faceMag have been defined. It defines any fields needed for just this algorithm.

cnEmFieldAlgorithm Macro Parameters

withNodalFields: Whether to create and update nodalE and nodalB. This is set to nonzero to beused with particles. With large implicitness, one may need to set maxcellxing for the particles.

8.2.23 Rad Port Macro File

This macro file can be imported to an input file with $ import radPort.

This macro file is available to the VSimEM and VSimMD packages.

A tuned phase-velocity port is an open or outgoing boundary condition. Waves traveling at exactly the speci-fied phase velocity of the boundary will exit the simulation with no reflection at all. Waves traveling at otherphase velocities will partially exit and partially reflect, with a power reflection oefficient of rho=(VphaseWave-VphaseBoundary)^2/(VphaseWave+VphaseBoundary)^2.

The user supplied phase-velocity is assumed to be that for normal incidence to the simualtion boundary. An additional1/cosine(angle) factor is applied to the phase velocity, where the angle is between the boundary normal and the linefrom the origin to the point on the boundary.

This boundary condition is subject to slow-time instability if there is metallic structure and associated fringe or nearfields too close to the boundary. For this reason, the boundary condition works best if used to bound a radiation typesimulation, where the boundary is sufficiently distant from the radiation source.

When working within a macro defined multifield (i.e. using yee) The RadPort can be defined with one simple macrocall, given below.

addRadPortBoundary Macro

addRadPortBoundary (position,VPHASE):

This macro is used to apply a port boundary optimized for a radiator at the origin with a macro generated multifield.It handles the before and after Ampere updaters as wells as inserting the update steps in the correct order.

addRadPortBoundary Macro Parameters

position: Which face to apply the port boundary, specified by lowerX,lowerY,lowerZ,upperX,upperYor upperZ.

VPHASE: Phase velocity tuning parameter, in meters/second.

If using a user defined multifield, the port must be applied once before, and once after the ampere updated. These twofunction calls are given below.

8.2. Macros present in Version 7 189

Page 194: VSim In Depth

VSim In Depth, Release 8.2.1

applyPortAtBoundary_beforeAmpere Macro

applyPortAtBoundary_beforeAmpere (IDIR,LOWERUPPER,VPHASE,DGRID,DT,EFIELD,NX,NY,NZ):

Use of this boundary requires that the Ampere updater properly omit updating of the electric fields at thedomain limits. This is insured when the Ampere updater looks like:

<FieldMultiUpdater yeeAmpere>kind = yeeAmpereUpdaterlowerBounds = [0 0 0]upperBounds = [NX NY NZ]contractFromBottomInNonComponentDir = 1..

</FieldMultiUpdater>

The “contractFromBottomInNonComponentDir = 1” being critical to this end.

The boundary is presently designed for cartesian dimensions only.

This macro should be called before the Ampere update steps

applyPortAtBoundary_beforeAmpere Macro Parameters

IDIR: 0,1,2 for the direction, x, y, or z, of the outgoing wave.

LOWERUPPER: 0,1 for the lower plane or upper plane, respectively.

VPHASE: Phase velocity tuning parameter, in meters/second.

DGRID: Cell size, e.g., DX, DY, or DZ, in the direction of IDIR, in front of boundary, in meters.

DT: Time step, in seconds.

EFIELD: Name of the Yee (edge) electric field use in the Ampere updater.

nx: Number of cells in x direction.

ny: Number of cells in y direction.

nz: Number of cells in z direction.

applyPortAtBoundary_afterAmpere Macro

applyPortAtBoundary_afterAmpere (IDIR,LOWERUPPER,VPHASE,DGRID,DT,EFIELD,NX,NY,NZ):

This macro should be called after the Ampere update steps

applyPortAtBoundary_afterAmpere Macro Parameters

IDIR: 0,1,2 for the direction, x, y, or z, of the outgoing wave

LOWERUPPER: 0,1 for the lower plane or upper plane, respectively

VPHASE: Phase velocity tuning parameter, in meters/second.

DGRID: Cell size, e.g., DX, DY, or DZ, in the direction of IDIR, in front of boundary, in meters.

DT: Time step, in seconds.

EFIELD: Name of the Yee (edge) electric field use in the Ampere updater.

190 Chapter 8. Macros

Page 195: VSim In Depth

VSim In Depth, Release 8.2.1

nx: Number of cells in x direction.

ny: Number of cells in y direction.

nz: Number of cells in z direction.

8.2.24 Perfect Dispersion Macro File

This macro file can be imported to an input file with $ import perfectDispersion.

This macro file is available to the VSimPA package.

This macro file consists of the macros necessary for defining the smoothed B update for dispersionless propagation.

For further information on the method used, please see [Cowan].

perfDispCoeffs Macro

perfDispCoeffs (DELTA, DXI, DYI, DZI):

Defines the perfect dispersion smoothing stencil coefficients.

perfDispCoeffs Macro Parameters

DELTA: The length of one cell.

DXI: 1/DX.

DYI: 1/DY.

DZI: 1/DZ.

perfectDispersionFaradayUpdaters Macro

perfectDispersionFaradayUpdaters (magField, elecField, DELTA, lb, ub):

A macro to define basic updaters for all 3 components.

perfectDispersionFaradayUpdaters Macro Parameters

magField: Name of the magnetic field.

elecField: Name of the electric field.

DELTA: The length of one cell.

lb: The lower bounds of the updater ( A vector i.e. [0 0 0]).

ub: The upper bounds of the updater ( A vector i.e. [NX NY NZ]).

perfDispPoissonSolver Macro

perfDispPoissonSolver (factor, beamBeta, boundary, DELTA, DXI, DYI, DZI):

Define an updater for a perfect dispersion Poisson solve. This is used for field initialization.

8.2. Macros present in Version 7 191

Page 196: VSim In Depth

VSim In Depth, Release 8.2.1

perfDispPoissonSolver Macro Parameters

factor: Factor to multiply the offsets by.

beamBeta: Normalized beam velocity.

boundary: Name of the grid boundary.

DELTA: The length of one cell.

DXI: 1/DX.

DYI: 1/DY.

DZI: 1/DZ.

perfDispDx Macro

perfDispDx (DXI, beamBeta,rowIdx, colIdx):

Define stencils for (negative) perfect dispersion forward derivatives in the moving frame. For the lab frame, setbeamBeta = 0. This macro is for the X-direction, Note that it does require the variables DELTA, DYI and DZI to allbe defined elsewhere in the simulation.

perfDispDx Macro Parameters

DXI: 1/DX.

beamBeta: Normalized beam velocity.

rowIdx: The row of the matrix to be filled.

colIdx: The column of the matrix to be filled.

perfDispDy Macro

perfDispDy (DYI,rowIdx, colIdx):

Define stencils for (negative) perfect dispersion forward derivatives in the moving frame. This macro is for the Y-direction, Note that it does require the variables DELTA, DXI and DZI to all be defined elsewhere in the simulation.

perfDispDy Macro Parameters

DYI: 1/DY.

rowIdx: The row of the matrix to be filled.

colIdx: The column of the matrix to be filled.

perfDispDz Macro

perfDispDx (DZI, beamBeta,rowIdx, colIdx):

Define stencils for (negative) perfect dispersion forward derivatives in the moving frame. This macro is for the Z-direction, Note that it does require the variables DELTA, DYI and DXI to all be defined elsewhere in the simulation.

192 Chapter 8. Macros

Page 197: VSim In Depth

VSim In Depth, Release 8.2.1

perfDispDz Macro Parameters

DZI: 1/DZ.

rowIdx: The row of the matrix to be filled.

colIdx: The column of the matrix to be filled.

perfDispPMLs Macro

perfDispPMLs (OUTLBx, OUTLBy, OUTLBz, OUTUBx, OUTUBy, OUTUBz, INLBx, INLBy, INLBz, INUBx,INUBy, INUBz,elecfield, magfield, pmlefield, pmlbfield, lybegin, lyend, lypml, lzbegin, lzend, lzpml):

This macro establishes perfect dispersion PML boundary conditions on the YZ faces of the simulation environment.Not that it does require the variables SIGMA_MAX, KAPPA_MAX, PML_EXP, DELTA to be defined elsewhere inthe simulation.

perfDispPMLs Macro Parameters

OUTLBx: Lower bound of the simulation in X (grid cells).

OUTLBy: Lower bound of the simulation in Y (grid cells).

OUTLBz: Lower bound of the simulation in Z (grid cells).

OUTUBx: Upper bound of the simulation in X (grid cells).

OUTUBy: Upper bound of the simulation in Y (grid cells).

OUTUBz: Upper bound of the simulation in Z (grid cells).

INLBx: Lower bound in X, excluding the PML region (grid cells).

INLBy: Lower bound in Y, excluding the PML region (grid cells).

INLBz: Lower bound in Z, excluding the PML region (grid cells).

INUBx: Upper bound in X, excluding the PML region (grid cells).

INUBy: Upper bound in Y, excluding the PML region (grid cells).

INUBz: Upper bound in Z, excluding the PML region (grid cells).

elecfield: The name of the electric field.

magfield: The name of the magnetic field.

pmlefield: The name of the electric field of the pml.

pmlbfield: The name of the magnetic field of the pml.

lybegin: The point at which the lower PML layer ends in the y-direction (m).

lyend: The point at which the upper PML layer begins in the y-direction (m).

lypml: The length of a PML layer in the y-direction (m).

lzbegin: The point at which the lower PML layer ends in the z-direction (m).

lzbegin: The point at which the upper PML layer begins in the z-direction (m).

lzpml: The length of a PML layer in the z-direction (m).

8.2. Macros present in Version 7 193

Page 198: VSim In Depth

VSim In Depth, Release 8.2.1

8.2.25 PML Macro File

This macro file can be imported to an input file with $ import pml.

This macro file is available to all packages.

This macro file applies a perfectly matched layer (PML) in the slab specified. PML’s provide boundary conditions forthe Yee algorithm that allows outgoing waves to leave without reflections (ideally).

There are two versions of this macro, one,pml, is for use when doing computations on a CPU, the other, gpupml, isused for computations on a GPU. They retain the exact same functionality, however GPU and CPU macros cannot bemixed.

applyPML Macro

applyPML (elecfield, magfield, nufieldname, nxl, nyl, nzl, nxu, nyu, nzu, pmldir, pmlsign, startval, delta, namebn,nameen, nameed, namebd):

OR

applyPML (elecfield, magfield, nufieldname, nxl, nyl, nzl, nxu, nyu, nzu, pmldir, pmlsign, startval, delta, namebn,nameen, nameed, namebd, dumpper):

OR

applyPML (elecfield, magfield, nufieldname, nxl, nyl, nzl, nxu, nyu, nzu, pmldir, pmlsign, startval, delta, namebn,nameen, nameed, namebd, dumpper, verb):

Note: One must use update step names that interleave properly with whatever Yee updater one is using. For the Yeemacro in the em.mac file, the updates are:

step1.0 - the first half B update step2.0 - the full E update step3.0 - the second half B update

so step0.5,step1.5,step2.5, and step3.5 are good choices for the four update names. The following line must be addedto the MultiField block to insure the steps occurin the correct order.

updateStepOrder = [step0.5 step1.0 step1.5 step2.0 step2.5 step3.0 step3.5]

applyPML Macro Parameters

elecfield: Name of the electric field.

magfield: Name of the magnetic field.

nufieldname: Name of the field to store nu profile.

nxl: Lower bound in the x direction.

nyl: Lower bound in the y direction.

nzl: Lower bound in the z direction.

nxu: Upper bound in the x direction.

nyu: Upper bound in the y direction.

nzu: Upper bound in the z direction.

pmdir: 0, 1, or 2 for the x, y, or z direction of the PML.

pmlsign: The sign of the outgoing direction.

194 Chapter 8. Macros

Page 199: VSim In Depth

VSim In Depth, Release 8.2.1

startval: Any offset of the grid start position in the direction of the PML (XSTART, YSTART, ZS-TART).

delta: The grid size in the PML direction.

namebn: A name for the bfield numerator damping update.

nameen: A name for the efield numerator damping update.

nameed: A name for the efield denominator damping update.

namebd: A name for the bfield denominator damping update.

dumpper: The dumpPeriod, if given

verb: The verbosity, if given

8.2.26 Port Macros File

This macro file can be imported to an input file with $ import port.

This macro file is available to the VSimEM or VSimMD packages.

A tuned phase-velocity port is an open or outgoing boundary condition. Waves traveling at exactly the specified phasevelocity of the boundary will exit the simulation with no reflection at all. Waves traveling at other phase velocities willpartially exit and partially reflect, with a power reflection coefficient of 𝜌 = (𝑣𝑝,𝑤𝑎𝑣𝑒 − 𝑣𝑝,𝑏𝑐)

2/(𝑣𝑝,𝑤𝑎𝑣𝑒 + 𝑣𝑝,𝑏𝑐)2.

An incident wave can be added as an option. If the incident wave travels at exactly the specified phase velocity, thewave will have exactly the specified form. If the incident wave has a different phase velocity, then its normalizationwill be not be exact. The incident wave can optionally be adjusted for feedback.

This boundary condition is subject to slow-time instability if there is metallic structure and associated fringe or nearfields too close to the boundary. For this reason, the boundary condition works best if used to terminate a length ofsmooth-walled waveguide, or to bound a radiation type simulation, where the boundary is sufficiently distant from theradiation source. The boundary is presently designed for cartesian dimensions.

Ports to be used with Macro generated multifields

addPortBoundary Macro

addPortBoundary (position,VPHASE):

This macro is used if adding a port boundary in conjunction with a macro generated multifield. It is not compatiblewith user generated multifields.

addPortBoundary Macro Parameters

position: Which face to apply the port boundary, specified by lowerX,lowerY,lowerZ,upperX,upperYor upperZ.

vphase: Phase velocity tuning parameter, in meters/second. For example, 𝑣𝑝 = 𝑐√(1−(𝑓𝑐𝑜/𝑓)2)

in a

waveguide.

8.2. Macros present in Version 7 195

Page 200: VSim In Depth

VSim In Depth, Release 8.2.1

addIncidentWaveAtPort Macro

addIncidentWaveAtPort (position,VPHASE,ICMP,FEEDBACKOPT,STFUNCIN):

This macro is designed to add a wave launcher which at a speciied phase-velocity on a port boundary. This is primarilyused for driving waveguides. It is intended to be used with a macro generated multifeld.

addIncidentWaveAtPort Macro Parameters

position: Either lowerX,lowerY,lowerZ,upperX,upperY or upperZ. The wave launcher will be appliedto the specified face.

vphase: Phase velocity tuning parameter, in meters/second. For example, 𝑣𝑝 = 𝑐√(1−(𝑓𝑐𝑜/𝑓)2)

in a

waveguide.

icmp: Incident wave’s component of the electric field. In many cases, both transverse components ofthe incident wave are nonzero, in which case there will be two invocations of addIncidentWaveAt-BoundaryPort, one for each component.

feedbackopt: If no feedback then feedbackopt = 0, or the name of the History providing thefeedback factor. See historystfunc-stfunc.

stfuncin: The function expression-stfunc providing the incident wave. This is often defined usinganother macro. See Defining Functions Using Macros. Note that this expression will be evaluatedat negative time, so it is common to use max(t,0.0) for time, to insure a zero value at negative times.

Example

$ import yee$ import port

# Add the portaddPortBoundary(lowerX,vphase(FREQ_CENTER))

# Port in the waveaddIncidentWaveAtPort(lowerX,vphase(FREQ_CENTER),1,0,CURR_→˓DENS*signalOuter(t)*waveguideEyProfile(y,z))

# Add MALs on top bottom and sidesaddMALBoundary(lowerY,2*WAVELENGTH)addMALBoundary(upperY,2*WAVELENGTH)

saveEmField()

Ports to be used with user defined multifields

If using a user defined multifield, call the first macro before the Ampere UpdateStep, and the second macro afterthe Ampere UpdateStep, as the names imply. Use of this boundary requires that the Ampere updater properly omitupdating of the electric fields at the domain limits. The contractFromBottomInNonComponentDir = 1 beingcritical to this end. These macros assume the MultiField setup for electromagnetics is being used.

196 Chapter 8. Macros

Page 201: VSim In Depth

VSim In Depth, Release 8.2.1

applyPortAtBoundary_beforeAmpere Macro

applyPortAtBoundary_beforeAmpere (idir,lowerupper,vphase,dgrid,dt,efield,nx,ny,nz):

defines all of the elements for tuned phase-velocity port that need to be applied before the Ampere UpdateStep. TheapplyPortAtBoundary_beforeAmpere macro is located in the file port.mac.

applyPortAtBoundary_afterAmpere Macro

applyPortAtBoundary_afterAmpere (idir,lowerupper,vphase,dgrid,dt,efield,nx,ny,nz):

defines all of the elements for tuned phase-velocity port that need to be applied after the Ampere UpdateStep. TheapplyPortAtBoundary_afterAmpere macro is located in the file port.mac.

addIncidentWaveAtBoundaryPort Macro

addIncidentWaveAtBoundaryPort (idir,lowerupper,vphase,dgrid,dt,efield,nx,ny,nz,imcp,feedbackopt,stfuncin):

Defines all of the elements to add an incident wave launcher at a tuned phase-velocity port boundary. The addInci-dentWaveAtBoundaryPort is located in the file port.mac.

applyPortAtBoundary_beforeAmpere / applyPortAtBoundary_afterAmpere / addIncidentWaveAt-BoundaryPort Macro Parameters

idir: 0,1,2 for the direction, x, y, or z, of the outgoing wave.

lowerupper: 0,1 for the lower plane or upper plane, respectively.

vphase: Phase velocity tuning parameter, in meters/second. For example, 𝑣𝑝 = 𝑐√(1−(𝑓𝑐𝑜/𝑓)2)

in a

waveguide.

dgrid: Cell size, e.g., dx, dy, or dz, in the direction of idir, in front of boundary, in meters.

dt: Time step, in seconds.

efield: Name of the Yee (edge) electric field use in the Ampere updater.

nx: Number of cells in the x direction.

ny: Number of cells in the x direction.

nz: Number of cells in the x direction.

Additional parameters for addIncidentWaveAtBoundaryPort Macro

icmp: Incident wave’s component of the electric field. In many cases, both transverse components ofthe incident wave are nonzero, in which case there will be two invocations of addIncidentWaveAt-BoundaryPort, one for each component.

feedbackopt: If no feedback then feedbackopt = 0, or the name of the History providing thefeedback factor. See historystfunc-stfunc.

stfuncin: The function expression-stfunc providing the incident wave. This is often defined usinganother macro. See Defining Functions Using Macros. Note that this expression will be evaluatedat negative time, so it is common to use max(t,0.0) for time, to insure a zero value at negative times.

8.2. Macros present in Version 7 197

Page 202: VSim In Depth

VSim In Depth, Release 8.2.1

Example

applyPortAtBoundary_beforeAmpere(0,1,vphaseWave,DX,DT,edgeE,NX,NY,NZ)<UpdateStep AmpereStep>

toDtFrac = 1.0updaters = [yeeAmpere]messageFields = [edgeE]

</UpdateStep>applyPortAtBoundary_afterAmpere(0,1,vphaseWave,DX,DT,edgeE,NX,NY,NZ)addIncidentWaveAtBoundaryPort(0,1,vphaseWave,DX,DT,edgeE,NX,NY,NZ,1,0,inputWave(x,y,z,→˓t))

8.2.27 Required Blocks Macro File

This macro file can be imported to an input file with $ import requiredBlocks.

This macro file is available to all packages.

This macro file creates the required plocks of the grid and decomp blocks as well as the required global variables.

Create Required Blocks Macro

createRequiredBlocks (dim,precision,timestep,numsteps,dumpperiod,nx,ny,nz,lx,ly,lz,sx,sy,sz): definesthe dimensionality,floattype,dt,nsteps,dumpPeriodicity variables as well as the Grid and Decomp Blocks. filerequiredBlocks.mac.

createRequiredBlocks Macro Parameters

dim: Dimensionality of the simulation domain.

precision: floattype of the simulation.

timestep: dt for the simulation.

numsteps: number of timesteps to run the simulation.

dumpperiod: the frequency of data dumps.

nx: number of cells in the x direction.

ny: number of cells in the y direction.

nz: number of cells in the z direction.

lx: length of domain in the x direction.

ly: length of domain in the y direction.

lz: length of domain in the z direction.

sx: start of simulation in the x direction (m).

sy: start of simulation in the y direction (m).

sz: start of simulation in z direction (m).

198 Chapter 8. Macros

Page 203: VSim In Depth

VSim In Depth, Release 8.2.1

Standard Time Step Macro

standardTimeStep (dmfrac,timestepFactor): Calculates the length of a time step, according to the Courant-Levy-Friedrichs condition. Returns a value, usage ($ DT = standardTimeStep(dmfrac,timestepFactor) )

standardTimeStep Macro Parameters

dmfrac: DeyMittraFraction, 1. if no grid boundaries are present.

timestepFactor: Safety factor by which to modify the timestep. Typically .9995.

8.2.28 Scattering Box Macro File

This macro file can be imported to an input file with $ import scatteringBox.

This macro file is available to the VSimEM package.

This macro file can be used to define a scattering box. In a scattering box a wave can be launched from an angle, andthe only waves that will leave the box are those which have been scattered off an object under test. In this macro theirare two main versions. The first, listed below is meant to work with a macro generated multifield. The other is actuallya set of three meant to work with a user generated multifield.

There are two versions of this macro, one, scatteringBox, is for use when doing computations on a CPU, the other,scatteringBoxGPU, is used for computations on a GPU. They retain the exact same functionality, however GPU andCPU macros cannot be mixed.

Scattering Box Macro

This particular macro comes in 3 varieties. There is scatteringBox, scatteringBox1Dielectric and scat-teringBox2Dielectric. scatteringBox is meant to be used if the simulation environment is a vacuum.scatteringBox1Dielectric is to be used if there is a uniform dielectric medium in the simulation space.scatteringBox2Dielectric is to be used if there are two seperate dielectrics in the simulation environment,and it is desired for the effects on EM waves caused by both dielectrics be confined to the scattering wavebox. They all use slightly different arguments, and have some constraints on how the dielectric is defineddelineated below.

scatteringBox (name,AMPLITUDE,FREQUENCY,WAVE_ANGLE_X,WAVE_ANGLE_Y,WAVE_ANGLE_Z,RISE_TIME,lx,ly,lz,ux,uy,uz):This macro will create a scattering box. The wave will be launched at a user specified angle, with a givenfrequency, amplitude and rise time. The size of the box is determine by the user (in grid cells). In this versionof the macro it is assumed that the background permittivity is vacuum.

scatteringBox1Dielectric (name,AMPLITUDE,FREQUENCY,WAVE_ANGLE_X,WAVE_ANGLE_Y,WAVE_ANGLE_Z,RISE_TIME,lx,ly,lz,ux,uy,uz,EPSILON_1):This macro will create a scattering box. The wave will be launched at a user specified angle, with a givenfrequency, amplitude and rise time. The size of the box is determine by the user (in grid cells). This macro alsowill allow for a uniform dielectric in the simulation space. This dielectric must be defined using the addDielec-tric macro and must be uniform across the simulation space. It is important to note that the electromagneticeffects of this dielectric will be confined to the scattering box. This is very useful if it is desired to observe onlythe waves scattered due to an object buried in dielectric. The Epsilon value of the dielectric must be defined.

scatteringBox2Dielectric (name,AMPLITUDE,FREQUENCY,WAVE_ANGLE_X,WAVE_ANGLE_Y,WAVE_ANGLE_Z,RISE_TIME,lx,ly,lz,ux,uy,uz,EPSILON_1,EPSILON_2,DIELECTRIC_1,DIELECTRIC_2,BOUNDARY,EPS_INTERSECTION):This macro will create a scattering box. The wave will be launched at a user specified angle, with a givenfrequency, amplitude and rise time. The size of the box is determine by the user (in grid cells). This macrosupports the ability to confine the electromagnetic effects of a wave impacting two dielectrics within thescattering wave box. For example the RCS of a ship in the ocean can be taken with the effects of wavesreflecting off the ocean cancelled out. You must seperately define the dielectric, using the addDielectric macro.

8.2. Macros present in Version 7 199

Page 204: VSim In Depth

VSim In Depth, Release 8.2.1

At the moment support is only provided for the dielectric intersection to exist on the Y-Z plane, and it must beuniform along the Y-Z plane.

scatteringBox Macro Parameters

name: Name of the scattering box.

AMPLITUDE: Amplitude of the wave launched within the scattering box.

FREQUENCY: Frequency of the wave launched within the scattering box.

WAVE_ANGLE_X: Angle of the launched wave as measured off the X axis (degrees).

WAVE_ANGLE_Y: Angle of the launched wave as measured off the Y axis (degrees).

WAVE_ANGLE_Z: Angle of the launched wave as measured off the Z axis (degrees).

RISE_TIME: Rise time of the launched wave.

lx: Lower bound of the scattered wave in the X-direction (grid cells).

ly: Lower bound of the scattered wave in the Y-direction (grid cells).

lz: Lower bound of the scattered wave in the Z-direction (grid cells).

ux: Upper bound of the scattered wave in the X-direction (grid cells).

uy: Upper bound of the scattered wave in the Y-direction (grid cells).

uz: Upper bound of the scattered wave in the Z-direction (grid cells).

EPSILON_1: Epsilon value of the 1st dielectric. (Only necessary for scatteringBox1Dielectric and scat-teringBox2Dielectric)

EPSILON_2: Epsilon value of the 2nd dielectric. (Only necessary for scatteringBox2Dielectric)

DIELECTRIC_1: Function defining the spatial profile of the first dielectric. (Only necessary for scat-teringBox2Dielectric)

DIELECTRIC_2: Function defining the spatial profile of the second dielectric. (Only necessary forscatteringBox2Dielectric)

BOUNDARY: Function describing the spatial profile of the first and second dielectric. It is important thatthe dielectric constant at the intersection be an average of the first and second dielectrics. (Onlynecessary for scatteringBox2Dielectric)

EPS_INTERSECTION: X-coordinate of the intersection of the first and second dielectrics. (Meters)(Only necessary for scatteringBox2Dielectric)

If using a user generated multifield, the following macros are to be used. Note that these macros do not support twodielectrics within the scattering box.

The user starts by making three setup calls, in this order:

fullScatteringBox_Region(xbgn,ybgn,zbgn,dx,dy,dz,dt,nx,ny,nz,nxBgnBox,nyBgnBox,nzBgnBox,nxEndBox,nyEndBox,nzEndBox,edgeDname,faceBname)fullScatteringBox_Wave(freq,cosx,cosy,cosz,ExR,EyR,EzR,ExI,EyI,EzI,epsRelBackground) fullScatter-ingBox_Updaters()

The first two, Region and Wave, can be anywhere in the input file, the third, Updaters, must be inside the MultiFieldblock.

The user must make this call just before the Ampere UpdateStep: fullScatteringBox_ApplyB()

The user must make this call just after the Ampere UpdateStep: fullScatteringBox_ApplyD()

200 Chapter 8. Macros

Page 205: VSim In Depth

VSim In Depth, Release 8.2.1

Full Scattering Box Region Macro

fullScatteringBox_Region (xbgn,ybgn,zbgn,dx,dy,dz,dt,nx,ny,nz,nxBgnBox,nyBgnBox,nzBgnBox,nxEndBox,nyEndBox,nzEndBox,edgeDname,faceBname):This macro establishes the region of the scattering box

fullScatteringBox_Region Macro Parameters

xbgn: The start point of the simulation in the X direction.

ybgn: The start point of the simulation in the Y direction.

zbgn: The start point of the simulation in the Z direction.

dx: Length of one cell in the X direction.

dy: Length of one cell in the Y direction.

dz: Length of one cell in the Z direction.

dt: Length of one timestep.

nx: Number of cells in the X direction in the simulation

ny: Number of cells in the Y direction in the simulation

nz: Number of cells in the Z direction in the simulation

nxBgnBox: The start point of the scattering box in the X direction (grid cells).

nyBgnBox: The start point of the scattering box in the Y direction (grid cells).

nzBgnBox: The start point of the scattering box in the Z direction (grid cells).

nxEndBox: The end point of the scattering box in the X direction (grid cells).

nyEndBox: The end point of the scattering box in the Y direction (grid cells).

nzEndBox: The end point of the scattering box in the Z direction (grid cells).

edgeDname: Name of the electric field used in the Ampere update.

faceBname: Name of the Magnetic field used in the Ampere update.

Full Scattering Box Wave Macro

fullScatteringBox_Wave (FREQUENCY,WAVE_ANGLE_X,WAVE_ANGLE_X,WAVE_ANGLE_X,ExR,EyR,EzR,ExI,EyI,EzI,EPSILON):This macro sets up the wave to be launched within the scattering box.

fullScatteringBox_Wave Macro Parameters

FRQUENECY: The frequency of the launched wave.

WAVE_ANGLE_X: Angle of the launched wave as measured off the X axis (degrees).

WAVE_ANGLE_Y: Angle of the launched wave as measured off the Y axis (degrees).

WAVE_ANGLE_Z: Angle of the launched wave as measured off the Z axis (degrees).

ExR: The real part of the amplitude in the X direction.

EyR: The real part of the amplitude in the Y direction.

EzR: The real part of the amplitude in the Z direction.

8.2. Macros present in Version 7 201

Page 206: VSim In Depth

VSim In Depth, Release 8.2.1

ExI: The imaginary part of the amplitude in the X direction. (Necessary for circular polarization)

EyI: The imaginary part of the amplitude in the Y direction. (Necessary for circular polarization)

EzI: The imaginary part of the amplitude in the Z direction. (Necessary for circular polarization)

EPSILON: The epsilon value within the scattering box. (1 for vacuum/air)

Full Scattering Box Updaters Macro

fullScatteringBox_Updaters (): This macro sets up the updaters necessary for the scatttering box to func-tion. It accepts no parameters but must be placed within the multifields block.

Full Scattering Box Apply B Macro

fullScatteringBox_ApplyB (): This macro must be called immediately before the Ampere UpdateStep.

Full Scattering Box Apply D Macro

fullScatteringBox_ApplyD (): This macro must be called immediately after the Ampere UpdateStep.

8.2.29 Smooth Macro File

This macro file can be imported to an input file with $ import smooth.

This macro file is available to all packages, but was created for the VSimPA examples.

This macro file provides some commands useful for smoothing fields like the current density field, which can helpwith mitigating numerical dispersion in the EM (Yee) field updates.

fourPassAndReloc Macro

fourPassAndReloc (name, J, J1, J2, S, nxlo, nylo, nzlo, nxhi, nyhi, nzhi,dir, dtfrac): Single-pass 1-2-1 digi-tal smoothing of all J components (3-d vector): Smooth the first aux field; write to the second

fourPassAndReloc Macro Parameters

name: Name for the updater

J: The depField to be smoothed

J1: The first auxiliary field in which J is copied

J2: The second auxiliary field used for smoothing. J2 should be used as an input of the yeeAmpereupdater

S: Stride of the stencil - usually 1

nxlo: Lower bound in X

nylo: Lower bound in Y

nzlo: Lower bound in Z

nxhi: Upper bound in X

202 Chapter 8. Macros

Page 207: VSim In Depth

VSim In Depth, Release 8.2.1

nyhi: Upper bound in Y

nzhi: Upper bound in Z

dir: The physical direction where the smoothing operator is applied (0: smoothing in the x direction,1:y, 2:z)

dtfrac: The fraction of the time step at which the currents are updated

fourPassAndRelocScalar Macro

fourPassAndRelocScalar (name, J, J1, J2, S, nxlo, nylo, nzlo, nxhi, nyhi, nzhi,dir, dtfrac): Single-pass 1-2-1 digital smoothing for a 1d-vector: Smooth the first aux field; write to the second

fourPassAndRelocScalar Macro Parameters

name: Name for the updater

J: The depField to be smoothed

J1: The first auxiliary field in which J is copied

J2: The second auxiliary field used for smoothing. J2 should be used as an input of the yeeAmpereupdater

S: Stride of the stencil - usually 1

nxlo: Lower bound in X

nylo: Lower bound in Y

nzlo: Lower bound in Z

nxhi: Upper bound in X

nyhi: Upper bound in Y

nzhi: Upper bound in Z

dir: The physical direction where the smoothing operator is applied (0: smoothing in the x direction,1:y, 2:z)

dtfrac: The fraction of the time step at which the currents are updated

Example usage

In order to use,

• include the macro,

• add two dummy fields of the same type as the field you want to smooth (eg Jaux, Jsmooth)

• before the Ampere update step apply the macro: fourPassAndReloc(smthBeam, Jdep, Jaux,Jsmooth, 1, 0, 0, 0, NX, NY, NZ, 0, 0.5)

• if you are using updateStepOrder, then the following should be manually added before theAmpere update smthBeamcopy, smthBeamsmooth1, smthBeamsmooth2, smthBeamsmooth3,smthBeamsmooth4 and smthBeamreloc

8.2. Macros present in Version 7 203

Page 208: VSim In Depth

VSim In Depth, Release 8.2.1

8.2.30 Smoothers Macro File

This macro file can be imported to an input file with $ import smoothers.

This macro file is available to all packages.

This macro file provides some commands useful for smoothing fields.

copyToAuxJ Macro

copyToAuxJ (name, restorefield, readfield, writefield): Copy a 4-vector field to a 3-vector field. This is necessaryfor smoothing currents, as one must copy to a field with ordinary messaging. Note that it does make use of thenumber of cells in the X,Y and Z directions as NX,NY,NZ

copyToAuxJ Macro Parameters

name: Name for the updater.

restorefield: Name of field from which to restore updater time upon restart. The smoothers shouldbe applied to the half-way time of an update step (toDtFrac=0.5). In order for restart to work, Vorpalneeds to know the time at a full step, not half. By setting the restorefield parameter to a field that issolved at a toDtFrac=1.0, Vorpal can properly restart. A good suggestion is to use an edgeE or faceBfield as in the example shown below. If using the yee.mac macro, the fields are named elecfield andmagfield explicitly.

readfield: The field to copy from.

writefield: The field to write to.

copyFromAuxJ Macro

copyFromAuxJ (name, restorefield, readfield, writefield): Copy to a 4-vector field from a 3-vector. After smooth-ing a field, it may need to be copied into a 4-vector field for the standard EM updates. Note that it does makeuse of the number of cells in the X,Y and Z directions as NX,NY,NZ

copyFromAuxJ Macro Parameters

name: Name for the updater.

restorefield: Name of field from which to restore updater time upon restart. The smoothers shouldbe applied to the half-way time of an update step (toDtFrac=0.5). In order for restart to work, Vorpalneeds to know the time at a full step, not half. By setting the restorefield parameter to a field that issolved at a toDtFrac=1.0, Vorpal can properly restart. A good suggestion is to use an edgeE or faceBfield as in the example shown below. If using the yee.mac macro, the fields are named elecfield andmagfield explicitly.

readfield: The field to copy from.

writefield: The field to write to.

yzsmth Macro

yzsmth (name, restorefield, updatefield, component, smfrac): Defines a yz-smoother for getting perfect EM dis-persion. The matrix is antismoother, but then a solve is done. Requires NX, NY, NZ, DX2, DYI2 DZI2

204 Chapter 8. Macros

Page 209: VSim In Depth

VSim In Depth, Release 8.2.1

yzsmth Macro Parameters

name: Name for the updater.

restorefield: The field from which the updater time is taken at restore. The smoothers should beapplied to the half-way time of an update step (toDtFrac=0.5). In order for restart to work, Vorpalneeds to know the time at a full step, not half. By setting the restorefield parameter to a field that issolved at a toDtFrac=1.0, Vorpal can properly restart. A good suggestion is to use an edgeE or faceBfield as in the example shown below. If using the yee.mac macro, the fields are named elecfield andmagfield explicitly.

updatefield: The field to be smoothed.

component: The component of the field to be smoothed.

smfrac: The amount of smoothing. The value of 1, when applied to the curl of B before adding to Egives perfect dispersion.

xsmth Macro

xsmth (name, restorefield, readfield, writefield, comp, sfac, ixbeg, ixend): Defines a x-smoother for modifyingthe EM dispersion. Start and stop values for smoothing are defined, as one may have to do something differentat the limits to preserve divergence. Requires NX, NY, NZ

xsmth Macro Parameters

name: Name for the updater.

restorefield: The field from which the updater time is taken at restore. The smoothers should beapplied to the half-way time of an update step (toDtFrac=0.5). In order for restart to work, Vorpalneeds to know the time at a full step, not half. By setting the restorefield parameter to a field that issolved at a toDtFrac=1.0, Vorpal can properly restart. A good suggestion is to use an edgeE or faceBfield as in the example shown below. If using the yee.mac macro, the fields are named elecfield andmagfield explicitly.

readfield: The field to be smoothed.

writefield: The field into which to put the smoothed result.

comp: The component of the field to be smoothed.

sfac: The smoothing factor, gives 1-2-1 when the value of this is one.

ixbeg: The x cell to begin at.

ixend: The x cell to end at.

smooth Macro

smooth (name, restorefield, readfield, writefield,smfacx,smfacy): Defines an xy-smoother for smoothing in x andy in one fell swoop. Requires NX, NY, NZ

smooth Macro Parameters

name: Name for the updater.

8.2. Macros present in Version 7 205

Page 210: VSim In Depth

VSim In Depth, Release 8.2.1

restorefield: The field from which the updater time is taken at restore. The smoothers should beapplied to the half-way time of an update step (toDtFrac=0.5). In order for restart to work, Vorpalneeds to know the time at a full step, not half. By setting the restorefield parameter to a field that issolved at a toDtFrac=1.0, Vorpal can properly restart. A good suggestion is to use an edgeE or faceBfield as in the example shown below. If using the yee.mac macro, the fields are named elecfield andmagfield explicitly.

readfield: The field to be smoothed.

writefield: The field into which to put the smoothed result.

smfacx: The smoothing factor for x. One for 1-2-1 smoothing.

smfacy: The smoothing factor for y. One for 1-2-1 smoothing.

smoothyz Macro

smoothyz (name, restorefield, readfield, writefield,smy,smz): Forward smoother for y and z at once. RequiresNDIM, NX, NY, NZ

smoothyz Macro Parameters

name: Name for the updater.

restorefield: The field from which the updater time is taken at restore. The smoothers should beapplied to the half-way time of an update step (toDtFrac=0.5). In order for restart to work, Vorpalneeds to know the time at a full step, not half. By setting the restorefield parameter to a field that issolved at a toDtFrac=1.0, Vorpal can properly restart. A good suggestion is to use an edgeE or faceBfield as in the example shown below. If using the yee.mac macro, the fields are named elecfield andmagfield explicitly.

readfield: The field to be smoothed.

writefield: The field into which to put the smoothed result.

smy: The smoothing factor to use for y. Unity gives standard 1/4, 1/2, 1/4 smoothing.

smz: The smoothing factor to use for z. Unity gives standard 1/4, 1/2, 1/4 smoothing.

copyxshft Macro

copyxshft (name, restorefield, readfield, writefield,comp,ixbeg,ixbmp): Updater to copy a component from an-other cell displaced in x

copyxshft Macro Parameters

name: Name for the updater.

restorefield: The field from which the updater time is taken at restore. The smoothers should beapplied to the half-way time of an update step (toDtFrac=0.5). In order for restart to work, Vorpalneeds to know the time at a full step, not half. By setting the restorefield parameter to a field that issolved at a toDtFrac=1.0, Vorpal can properly restart. A good suggestion is to use an edgeE or faceBfield as in the example shown below. If using the yee.mac macro, the fields are named elecfield andmagfield explicitly.

readfield: The field to be smoothed.

206 Chapter 8. Macros

Page 211: VSim In Depth

VSim In Depth, Release 8.2.1

writefield: The field into which to put the smoothed result.

ixbeg: The cell in the x direction that is copied into.

ixbmp: The x index displacement to the cell that is copied from.

Example use of the smoothers

## Current smoothing. Copy J, smooth, copy back.## Copy first. Cannot smooth directly on SumRhoJ as not valid in guard cellscopyToAuxJ(copyjbeg, faceB, SumRhoJ, auxRhoJ1)

# y-z smoothing of current goes over entire region.smoothyz(jsmoothyz, faceB, auxRhoJ1, auxRhoJ2, 1.0, 1.0)

# x smoothing by component basis required for charge conservation# y and z components copied in place in last cells prior to smoothing.# Gives 3/4, 1/4 in last cells.copyxshft(copyjydn, faceB, auxRhoJ2, auxRhoJ2, 1, -1, 1)copyxshft(copyjyup, faceB, auxRhoJ2, auxRhoJ2, 1, NX, -1)copyxshft(copyjzdn, faceB, auxRhoJ2, auxRhoJ2, 2, -1, 1)copyxshft(copyjzup, faceB, auxRhoJ2, auxRhoJ2, 2, NX, -1)

# x components in first and last cell copied over, not smoothed, for charge# conservationcopyxshft(copyjxdn, faceB, auxRhoJ2, auxRhoJ1, 0, 0, 0)copyxshft(copyjxup, faceB, auxRhoJ2, auxRhoJ1, 0, $NX-1$, 0)

# x component not smoothed in first or last cell for charge conservationxsmth(jxsmoothx, faceB, auxRhoJ2, auxRhoJ1, 0, 1., 1, $NX-1$)

# y and z components smoothed throughout interiorxsmth(jysmoothx, faceB, auxRhoJ2, auxRhoJ1, 1, 1., 0, NX)xsmth(jzsmoothx, faceB, auxRhoJ2, auxRhoJ1, 2, 1., 0, NX)

# Copy back. DO NOT message, as SumRhoJ messaging adds in from other ranks.copyFromAuxJ(copyjend, faceB, auxRhoJ1, SumRhoJ)

8.2.31 Solverbcs Macro File

This macro file can be imported to an input file with $ import solverbcs.

This macro file is available to all packages.

This macro file sets up boundary conditions for electrostatic simulations.

dirichletBC Macro

dirichletBC (name, md, lbx, lby, lbz, ubx, uby, ubz, comp, exp, scl): This macro establishes a dirichlet bound-ary condition for electrostatic solvers

8.2. Macros present in Version 7 207

Page 212: VSim In Depth

VSim In Depth, Release 8.2.1

dirichletBC Macro Parameters

name: Name of the boundary condition.

md: The minimum dimension needed for this boundary condition.

lbx: The lower-x bound over which this is applied.

lby: The lower-y bound over which this is applied.

lbz: The lower-z bound over which this is applied.

ubx: The upper-x bound over which this is applied.

uby: The upper-y bound over which this is applied.

ubz: The upper-z bound over which this is applied.

comp: The component (row of the matrix) being filled.

exp: The expression for the function defining the value.

scl: The scaling applied to all matrix and vector entries.

neumannBC Macro

neumannBC (name, md, lbx, lby, lbz, ubx, uby, ubz, comp, exp, dir, pm, scl)

This macro establishes a Neumann boundary condition for electrostatic solvers

neumannBC Macro Parameters

name: Name of the boundary condition.

md: The minimum dimension needed for this boundary condition.

lbx: The lower-x bound over which this is applied.

lby: The lower-y bound over which this is applied.

lbz: The lower-z bound over which this is applied.

ubx: The upper-x bound over which this is applied.

uby: The upper-y bound over which this is applied.

ubz: The upper-z bound over which this is applied.

comp: The component (row of the matrix) being filled.

exp: The expression for the function defining the value.

dir: 0, 1 or 2 for if the boundary condition is on the X, Y, or Z, boundary.

pm: ‘+1’ for the low side, ‘-1’ for the high side.

scl: The scaling applied to all matrix and vector entries.

dirichletFromField Macro

dirichletFromField (name, md, lbx, lby, lbz, ubx, uby, ubz, comp, field, fcomp, scl) This macro estab-lishes a dirichlet boundary condition for electrostatic solvers from a fiseld.

208 Chapter 8. Macros

Page 213: VSim In Depth

VSim In Depth, Release 8.2.1

dirichletFromField Macro Parameters

name: Name of the boundary condition.

md: The minimum dimension needed for this boundary condition.

lbx: The lower-x bound over which this is applied.

lby: The lower-y bound over which this is applied.

lbz: The lower-z bound over which this is applied.

ubx: The upper-x bound over which this is applied.

uby: The upper-y bound over which this is applied.

ubz: The upper-z bound over which this is applied.

comp: The component (row of the matrix) being filled.

field: The field name.

fcomp: The component of the field to be used.

scl: The scaling applied to all matrix and vector entries.

8.2.32 Specular Box Macro File

This macro file can be imported to an input file with $ import specularBox.

This macro file is available to all packages.

reflectingBox (LEFTPLATE, RIGHTPLATE, FRONTPLATE, BACKPLATE, BOTTOMPLATE, TOPPLATE):

Sets up fully reflecting boxes in any dimension. Note that this macro does not take as arguments, but needsNX, NY, NZ, XSTART, YSTART, ZSTART, DX, DY, DZ

reflectingBox Macro Parameters

LEFTPLATE: Position of left (in x) reflecting surface.

RIGHTPLATE: Position of right (in x) reflecting surface.

FRONTPLATE: Position of front (in y) reflecting surface.

BACKPLATE: Position of back (in y) reflecting surface.

BOTTOMPLATE: Position of bottom (in z) reflecting surface.

TOPPLATE: Position of top (in z) reflecting surface.

reflectingBoxCylindrical (ZLOWER,RLOWER,ZUPPER,RUPPER):

Sets up fully reflecting boxes in any dimension for simulations performed in cylindrical coordinates. Currently this reflecting box can only be set up along the edges of the simulation space.Note that this macro does not take as arguments, but needs NZ, NR, NPHI

This macro is encrypted and available with the VSimBase license.

8.2. Macros present in Version 7 209

Page 214: VSim In Depth

VSim In Depth, Release 8.2.1

reflectingBoxCylindrical Macro Parameters

ZLOWER: Position of the reflecting surface on the lower Z surface (m). If left blank a reflecting surfacewill not be placed here.

RLOWER: Position of the reflecting surface on the lower R surface (m). If left blank a reflecting surfacewill not be placed here.

ZUPPER: Position of the reflecting surface on the upper Z surface (m). If left blank a reflecting surfacewill not be placed here.

RUPPER: Position of the reflecting surface on the upper R surface (m). If left blank a reflecting surfacewill not be placed here.

8.2.33 Statics Macro File

This macro file can be imported to an input file with $ import statics.

This macro file is available to all packages.

This poorly-named macro file aids in the creation of Laplacians used in electro- and magneto-statics problems.

Laplacian Macro

laplacian (name, md, lbx, lby, lbz, ubx, uby, ubz, comp, fld, fcomp, dcoeff, xcoeff, ycoeff, zcoeff): Laplacian

This macro is encrypted and available with the VSimBase License

Laplacian Macro Parameters

name: The base name of the boundary condition.

md: The minimum dimension needed for this boundary condition.

lbx: The lower bound over which this is applied in the X-direction.

lby: The lower bound over which this is applied in the Y-direction.

lbz: The lower bound over which this is applied in the Z-direction.

ubx: The upper bound over which this is applied in the X-direction.

uby: The upper bound over which this is applied in the Y-direction.

ubz: The upper bound over which this is applied in the Z-direction.

comp: The component (row of the matrix) being filled.

fld: The name of the field used to fill the associated source (RHS) vector.

fcomp: The component of the field.

dcoeff: Diagonal coefficient.

xcoeff: Coefficient for x offset stencils.

ycoeff: Coefficient for y offset stencils.

zcoeff: Coefficient for z offset stencils.

210 Chapter 8. Macros

Page 215: VSim In Depth

VSim In Depth, Release 8.2.1

STFunc Laplacian Macro

stFuncLaplacian (name, md, lbx, lby, lbz, ubx, uby, ubz, comp, fld, fcomp, xcoeff, ycoeff, zcoeff, func):Laplacian whose matrix entries are calculated using an STFunc.

This macro is encrypted and available with the VSimBase License

STFunc Laplacian Macro Parameters

name: The base name of the boundary condition.

md: The minimum dimension needed for this boundary condition.

lbx: The lower bound over which this is applied in the X-direction.

lby: The lower bound over which this is applied in the Y-direction.

lbz: The lower bound over which this is applied in the Z-direction.

ubx: The upper bound over which this is applied in the X-direction.

uby: The upper bound over which this is applied in the Y-direction.

ubz: The upper bound over which this is applied in the Z-direction.

comp: The component (row of the matrix) being filled.

fld: The name of the field used to fill the associated source (RHS) vector.

fcomp: The component of the field.

dcoeff: Diagonal coefficient.

xcoeff: Coefficient for x offset stencils.

ycoeff: Coefficient for y offset stencils.

zcoeff: Coefficient for z offset stencils.

func: The expression for the function defining the value.

Coord Prod Laplacian Macro

coordProdLaplacian (name, md, lbx, lby, lbz, ubx, uby, ubz, comp, fld, fcomp, scl, func): This macro is fora laplacian on variable (coordProd) grids.

This macro is encrypted and available with the VSimBase License

Coord Prod Laplacian Macro Parameters

name: The base name of the boundary condition.

md: The minimum dimension needed for this boundary condition.

lbx: The lower bound over which this is applied in the X-direction.

lby: The lower bound over which this is applied in the Y-direction.

lbz: The lower bound over which this is applied in the Z-direction.

ubx: The upper bound over which this is applied in the X-direction.

uby: The upper bound over which this is applied in the Y-direction.

8.2. Macros present in Version 7 211

Page 216: VSim In Depth

VSim In Depth, Release 8.2.1

ubz: The upper bound over which this is applied in the Z-direction.

comp: The component (row of the matrix) being filled.

fld: The name of the field used to fill the associated source (RHS) vector.

fcomp: The component of the field.

scl: The scaling factor by which all matrix elements will be multiplied.

func: The expression for the function defining the value.

Curl Curl Macro

Curl Curl (name, md, lbx, lby, lbz, ubx, uby, ubz, comp, fld, fcomp, dir, pm, dcoeff, tcoeff1, tcoeff2, ncoeff1,ncoeff2):

This macro is encrypted and available with the VSimBase License

Curl Curl Macro Parameters

name: The base name of the boundary condition.

md: The minimum dimension needed for this boundary condition.

lbx: The lower bound over which this is applied in the X-direction.

lby: The lower bound over which this is applied in the Y-direction.

lbz: The lower bound over which this is applied in the Z-direction.

ubx: The upper bound over which this is applied in the X-direction.

uby: The upper bound over which this is applied in the Y-direction.

ubz: The upper bound over which this is applied in the Z-direction.

comp: The component (row of the matrix) being filled.

fld: The name of the field used to fill the associated source (RHS) vector.

fcomp: The component of the field.

dir: The scaling factor by which all matrix elements will be multiplied.

pm: The expression for the function defining the value.

dcoeff: The expression for the function defining the value.

tcoeff1: The expression for the function defining the value.

tcoeff2: The expression for the function defining the value.

ncoeff1: The expression for the function defining the value.

ncoeff2: The expression for the function defining the value.

8.2.34 Verbosity Macro File

This macro file can be imported to an input file with $ import verbosity.

This macro file is available to all packages.

This macro file simply contains some constants for use in creating an input file.

212 Chapter 8. Macros

Page 217: VSim In Depth

VSim In Depth, Release 8.2.1

After importing, it can be used by setting verbosity = VPM_NOTICE or the appropriate level.

The verbosity levels are as follows:

$ VPM_EMERGENCY$ VPM_ALERT$ VPM_CRITICAL$ VPM_ERROR$ VPM_WARNING$ VPM_NOTICE$ VPM_INFO$ VPM_DEBUG$ VPM_DEBUG2$ VPM_DEBUG3

8.2.35 Yee Macro File

This macro file can be imported to an input file with

:: $ import yee

This macro file is available to all packages.

This macro file contains several powerful functions that allow for an easily reconfigurable multifield to handle simu-lations with no particles. The macros contained here are incompatible with a user generated multifield.

There is a second version of this macro, yeeGPU. It retains most of the same functionality with some exceptions. Themacros available under yeeGPU can be found in YeeGPU Macro File

saveEmField Macro

saveEmField (): This macro saves the EmField as well as all current sources and boundary conditions definedusing the other function calls. The default value for the name of the field is ‘emField’.

saveEmField (gridBoundary): The name of a grid boundary must be specified if it is used in the simulation. Thedefault value for the name of the field is ‘emField’.

saveEmField (gridBoundary,name): In the event two seperate multifields are used in one file, they must be namedto be differentiated from eachother.

saveEmField Macro Parameters

gridboundary (string): Name of the grid boundary.

name (string): Name of the multifield.

addParticleFields Macro

addParticleFields (): This macro will add two fields, nodalE and nodalB to the simulation. These fields canthen be used in particle species blocks.

8.2. Macros present in Version 7 213

Page 218: VSim In Depth

VSim In Depth, Release 8.2.1

addCurrentSource Macro

addCurrentSource(name,polarization,profile,lx,ly,lz,ux,uy,uz)

This macro adds a current source (writing to the J field) with a user defined profile in the user definedupdate region.

addCurrentSource Macro Parameters

name (string): Name of the current source.

polarization (integer): Direction in which the wave is polarized. This is a coordinate system de-pendent quantity. In Cartesian coordinates 0=x, 1=y, 2=z.

profile: The function that defines the current source’s amplitude, frequency and phase shift.

lx (float): Lower bound in the x direction (meters).

ly (float): Lower bound in the y direction (meters).

lz (float): Lower bound in the z direction (meters).

ux (float): Upper bound in the x direction (meters).

uy (float): Upper bound in the y direction (meters).

uz (float): Upper bound in the z direction (meters).

addToCurrentSource Macro

addToCurrentSource (name,polarization,profile,lx,ly,lz,ux,uy,uz):

This macro adds a current source (additive to the J field) with a user defined profile in the user defined update region.The profile expression will be reevaluated and added each time step.

addToCurrentSource Macro Parameters

name (string): Name of the current source.

polarization (integer): Direction in which the wave is polarized. This is a coordinate system de-pendent quantity. In Cartesian coordinates 0=x, 1=y, 2=z.

profile (string): An inline expression to be evaluated. This function typically defines the currentsource’s amplitude, frequency and phase shift.

lx (float): Lower bound in the x direction (meters).

ly (float): Lower bound in the y direction (meters).

lz (float): Lower bound in the z direction (meters).

ux (float): Upper bound in the x direction (meters).

uy (float): Upper bound in the y direction (meters).

uz (float): Upper bound in the z direction (meters).

214 Chapter 8. Macros

Page 219: VSim In Depth

VSim In Depth, Release 8.2.1

addWaveLauncher Macro

addWaveLauncher (name,polarization,profile,position):

addWaveLauncher (name,polarization,profile,lx,ly,lz,ux,uy,uz):

Launches a wave directly into the simulation domain by imposing an E-field on a specified boundary face.

If the wave launcher is to be placed anywhere other than on a domain boundary face, upper and lowerbounds (in meters) may be specified instead.

addWaveLauncher Macro Parameters

name (string): Name of the wave launcher.

polariziation (integer): Direction in which the wave is polarized. This is a coordinate systemdependent quantity. In Cartesian coordinates 0=x, 1=y, 2=z.

profile (string): An inline expression to be evaluated. This function typically defines the currentsource’s amplitude, frequency and phase shift.

position (string): Face on whcih the wave launcher will be applied to (low-erX,lowerY,lowerZ,upperX,upperY, upperZ ).

lx (float): Lower bound in the x direction (meters).

ly (float): Lower bound in the y direction (meters).

lz (float): Lower bound in the z direction (meters).

ux (float): Upper bound in the x direction (meters).

uy (float): Upper bound in the y direction (meters).

uz (float): Upper bound in the z direction (meters).

addToWaveLauncher Macro

addToWaveLauncher (name,polarization,func,position):

addToWaveLauncher (name,polarization,func,lx,ly,lz,ux,uy,uz):

A type of wave launcher that adds a wave function to the existing E-field on a specified boundary face.The function will be re-evaluated and added each timestep.

If the additive wave launcher is to be used on top of a regular setter wave launcher (i.e. one of typeaddWaveLauncher) then make sure this is called second so that it will not be overwritten.

If the wave launcher is to be placed anywhere other than on a domain boundary face, upper and lowerbounds (in cell indices) may be specified instead:

addToWaveLauncher Macro Parameters

name: Name of the wave launcher.

polariziation (integer): Direction in which the wave is polarized. This is a coordinate systemdependent quantity. In Cartesian coordinates 0=x, 1=y, 2=z.

func: A function describing the form of the added wave.

8.2. Macros present in Version 7 215

Page 220: VSim In Depth

VSim In Depth, Release 8.2.1

position: Face on which to apply the wave launcher (lowerX, lowerY, lowerZ, upperX, upperY, up-perZ).

lx: Lower bound in the x direction (meters).

ly: Lower bound in the y direction (meters).

lz: Lower bound in the z direction (meters).

ux: Upper bound in the x direction (meters).

uy: Upper bound in the y direction (meters).

uz: Upper bound in the z direction (meters).

addAngledWaveLauncher Macro

addAngledWaveLauncher (name,FREQUENCY,WAVE_ANGLE_X,WAVE_ANGLE_Y,WAVE_ANGLE_Z,TRISE,AMPLITUDE,lx,ly,lz,ux,uy,uz):This macro will create a port from which a wave can be launched at a user specified angle in the X, Y and Zdirections.

addAngledWaveLauncher Macro Parameters

name: Name of the wave launcher.

FREQUENCY: Frequency of the launched wave.

WAVE_ANGLE_X: Angle as measured off the X-axis of the launched wave.

WAVE_ANGLE_Y: Angle as measured off the Y-axis of the launched wave.

WAVE_ANGLE_Z: Angle as measured off the Z-axis of the launched wave.

TRISE: Rise time of the launched wave to full amplitude.

AMPLITUDE: Maximum amplitude of the launched wave.

lx: Lower bound in the x direction (meters).

ly: Lower bound in the y direction (meters).

lz: Lower bound in the z direction (meters).

ux: Upper bound in the x direction (meters).

uy: Upper bound in the y direction (meters).

uz: Upper bound in the z direction (meters).

addCircularWaveLauncher Macro

addCircularWaveLauncher (name,FREQUENCY,TRISE,AMPLITUDE,lx,ly,lz,ux,uy,uz): This macro willcreate a port from which a circularly polarized wave is launched.

addCircularWaveLauncher Macro Parameters

name: Name of the wave launcher.

FREQUENCY: Frequency of the launched wave.

AMPLITUDE: Maximum amplitude of the launched wave.

216 Chapter 8. Macros

Page 221: VSim In Depth

VSim In Depth, Release 8.2.1

lx: Lower bound in the x direction (meters).

ly: Lower bound in the y direction (meters).

lz: Lower bound in the z direction (meters).

ux: Upper bound in the x direction (meters).

uy: Upper bound in the y direction (meters).

uz: Upper bound in the z direction (meters).

addPort Macro

addPort (position,vphase,polarization,waveProfile):

This macro adds a port boundary condition to your simulation. A port combines an open boundary con-dition with a wave launcher. It is most commonly used for microwave device simulations. The boundaryis open to waves with phase velocity sharply peaked around vphase. It rapidly becomes infectual as theincident phase velocity deviates from vphase. If a multi-component incoming wave is desired, use theaddIncidentWaveAtPort macro in port.mac instead: Port Macros File.

addPort Macro Parameters

position: The face at which to apply the port boundary. You can specify lowerX, lowerY, lowerZ,upperX, upperY, or upperZ.

vphase (float): Phase velocity of the outgoing wave expected at the boundary. Velocity should be themagnitude of the component that lies along the outward facing normal at the boundary face. Theboundary will be open to this phase velocity and a narrow band around it. Note that the sign of thephase velocity should be a positive number; its sign will be taken care of automatically.

polarization (integer): Direction in which the wave is polarized. This is a coordinate system de-pendent quantity. In Cartesian coordinates 0=x, 1=y, 2=z. If no incoming wave is desired, you muststill specify a number here.

waveProfile (string): Mathematical expression of the wave function in terms of x, y, z, t. If noincoming wave is desired, type None.

addConductingBoundary Macro

addConductingBoundary (position): This macro creates an electrically conducting boundary condition on theface specified by the position parameter.

addConductingBoundary Macro Parameters

position: Face the boundary condition will be applied to (lowerX,lowerY,lowerZ,upperX,upperY orupperZ).

addMagneticBoundary Macro

addMagneticBoundary (position): This macro creates a magnetically conducting boundary condition on theface specified by the position parameter.

8.2. Macros present in Version 7 217

Page 222: VSim In Depth

VSim In Depth, Release 8.2.1

addMagnetic Boundary Macro Parameters

position: Face the boundary condition will be applied to (lowerX,lowerY,lowerZ,upperX,upperY orupperZ).

addMALBoundary Macro

addMALBoundary (position,thickness): This macro creates a MAL (Matched Absorbing Layer) boundary condi-tion on the face specified in position and thickness of the difference between its upper and lower bounds.

addMALBoundary Macro Parameters

position: Face the boundary condition will be applied to (lowerX,lowerY,lowerZ,upperX,upperY orupperZ).

thickness (float): The thickness of the MAL boundary (m).

addOpenBoundary Macro

addOpenBoundary (position): This macro creates an open boundary condition on the face specified by the posi-tion parameter.

addOpenBoundary Macro Parameters

position: Face the boundary condition will be applied to (lowerX,lowerY,lowerZ,upperX,upperY orupperZ).

addPMLBoundary Macro

addPMLBoundary (position0,position1,position2,position3,position4,position5,energyWritePeriod,THICKNESS,SIGMA_MAX,PML_EXP):

This macro creates a PML region on each of the faces specified, of the thickness specified. In addition the PML isgiven a user defined conductivity.

addPMLBoundary Macro Parameters

position0: If lowerX is used as an argument for this parameter the PML layer will be applied to thelow end of the Y-Z plane.

position1: If lowerY is used as an argument for this parameter the PML layer will be applied to thelow end of the X-Z plane.

position2: If lowerZ is used as an argument for this parameter the PML layer will be applied to thelow end of the X-Y plane.

position3: If upperX is used as an argument for this parameter the PML layer will be applied to thehigh end of the Y-Z plane.

position4: If upperY is used as an argument for this parameter the PML layer will be applied to thehigh end of the X-Z plane.

218 Chapter 8. Macros

Page 223: VSim In Depth

VSim In Depth, Release 8.2.1

position5: If upperZ is used as an argument for this parameter the PML layer will be applied to thehigh end of the X-Y plane.

energyWritePeriod: Number of time steps between having the energy dissipated by the PMLrecorded.

THICKNESS: Thickness of the PML layer (in meters).

SIGMA_MAX: A constant divided by epsilon_0 or mu_0 for electric or magnetic conductivity (i.e.3*LIGHTSPEED/DX).

PML_EXP: Power-law exponent of sigma functional form (most commonly 4).

turnOn Macro

turnOn (t,RISE_TIME):

Macro to slowly turn on an excitation source. It follows a sine squared growth profile.

turnOn Macro Parameters

t: Time variable.

RISE_TIME: Amount of time to turn on the excitation (s).

launchWaveFromPort Macro

launchWaveFromPort (position,polarization,freq,cutoff_freq,amp,grid_loc): This macro specifies a port(with amp, grid_loc and position) and then launches a wave from it.

If not applied to an entire face, upper and lower bounds (in grid cells) can be defined using the arguments below

launchWaveFromPort (posname,polarization,freq,amp,direction,lx,ly,lz,ux,uy,uz):

launchWaveFromPort Macro Parameters

position: Face the port will be applied to (lowerX,lowerY,lowerZ,upperX,upperY or upperZ).

posname: Name of user defined launch position.

polarization: Direction in which the wave is polarized. This is a coordinate system dependentquantity. In Cartesian coordinates 0=x, 1=y, 2=z.

freq: Frequency of the launched wave.

cutoff_freq: Cutoff frqenecy of the launched wave.

amp: Amplitude of the launched wave.

grid_loc: Location of the port on the face determined by position.

lx: Lower bound in the x direction (meters).

ly: Lower bound in the y direction (meters).

lz: Lower bound in the z direction (meters).

ux: Upper bound in the x direction (meters).

uy: Upper bound in the y direction (meters).

8.2. Macros present in Version 7 219

Page 224: VSim In Depth

VSim In Depth, Release 8.2.1

uz: Upper bound in the z direction (meters).

calculateSAR Macro

calculateSAR (gridBoundary,Epsilon,Sigma): This macro will calculate the specific absorption rate of a givengeometry with a user defined permittivity and conductivity.

calculateSAR Macro Parameters

gridBoundary: The geometry describing the object to calcualte the specific absortion rate in.

Epsilon: The permittivity of the grid boundary.

Sigma: The conductivity of the grid boundary.

addThinWireModel Macro

addThinWireModel (name,wireAxis,lx,ly,lz,ux,uy,uz,sc0,sc1): This macro will create a thin wire in the volumespecified. To use this macro a volume and the longitudinal axis of the wire must be specified. The wire is thenscaled to a size of the volume by the scaling factors specified, allowing for the creation of an infintesimally thinwire.

addThinWireModel Macro Parameters

name: Name of the wire.

wireAxis: Longitudinal axis of the wire.

lx: Lower bound in the x direction (grid cells).

ly: Lower bound in the y direction (grid cells).

lz: Lower bound in the z direction (grid cells).

ux: Upper bound in the x direction (grid cells).

uy: Upper bound in the y direction (grid cells).

uz: Upper bound in the z direction (grid cells).

sc0: Scaling factor applied to the size of a grid cell. If wireAxis = 0 or 2, sc0 is applied on the y-axis, ifwireAxis = 1, sc0 is applied on the x-axis

sc1: Upper bound in the z direction (grid cells). If wireAxis = 0 or 1 sc1 is applied on the z-axis, ifwireAxis = 2, sc1 is applied on the x-axis.

8.2.36 YeeGPU Macro File

This macro file can be imported to an input file with $ import yeeGPU.

This macro file is available to the VSimEM package.

This macro file contains several powerful functions that allow for an easily reconfigurable multifield to handle sim-ulations with no particles. The macros contained here are incompatible with a user generated multifield. It is to beused when running simulations on a GPU It can be imported to an input file with $ import yeeGPU. There is a secondversion of this macro, yee It contains some advanced functions, but otherwise their operation is the exact same.

220 Chapter 8. Macros

Page 225: VSim In Depth

VSim In Depth, Release 8.2.1

saveEmField Macro

saveEmField (): This macro saves the EmField as well as all current sources and boundary conditions definedusing the other function calls.

saveEmField (gridBoundary): The name of a grid boundary must be specified if it is used in the simulation.

saveEmField (gridBoundary,name): In the event two seperate multifields are used in one file, they must be namedto be differentiated from eachother.

saveEmField Macro Parameters

gridboundary: Name of the grid boundary.

name: Name of the multifield.

setCurrentSource Macro

setCurrentSource (name,polarization,profile): This macro sets a current source (writing to the J field) with auser defined profile and spatial region. Note that if bounds aren’t set explicitly computational speed is marginallyimpacted.

setCurrentSource (name,polarization,profile,lx,ly,lz,ux,uy,uz): This macro sets a current source (writing tothe J field) with a user defined profile in the user defined update region. By setting lower and upper boundsexplicitly computational effiency is advanced

setCurrentSource Macro Parameters

name: Name of the current source.

polarization (integer): Direction in which the wave is polarized. This is a coordinate system de-pendent quantity. In Cartesian coordinates 0=x, 1=y, 2=z.

profile: The function that defines the current source’s amplitude, frequency and phase shift.

lx: Lower bound in the x direction (meters).

ly: Lower bound in the y direction (meters).

lz: Lower bound in the z direction (meters).

ux: Upper bound in the x direction (meters).

uy: Upper bound in the y direction (meters).

uz: Upper bound in the z direction (meters).

addCurrentSource Macro

addCurrentSource (name,polarization,profile): This macro sets a current source (writing to the J field) with auser defined profile in the user defined update region. Note that if bounds aren’t set explicitly computationalspeed is marginally impacted.

addCurrentSource (name,polarization,profile,lx,ly,lz,ux,uy,uz): This macro adds a current source (writing tothe J field) with a user defined profile in the user defined update region. An added current source will add to theJ field in the update region, as opposed to overwriting with a new value as in setCurrentSource

8.2. Macros present in Version 7 221

Page 226: VSim In Depth

VSim In Depth, Release 8.2.1

addCurrentSource Macro Parameters

name: Name of the current source.

polarization (integer): Direction in which the wave is polarized. This is a coordinate system de-pendent quantity. In Cartesian coordinates 0=x, 1=y, 2=z.

profile: The function that defines the current source’s amplitude, frequency and phase shift.

lx: Lower bound in the x direction (meters).

ly: Lower bound in the y direction (meters).

lz: Lower bound in the z direction (meters).

ux: Upper bound in the x direction (meters).

uy: Upper bound in the y direction (meters).

uz: Upper bound in the z direction (meters).

turnOn Macro

turnOn (t,RISE_TIME):

Macro to slowly turn on an excitation source. It follows a sine squared growth profile.

turnOn Macro Parameters

t: Time variable.

RISE_TIME: Amount of time to turn on the excitation (s).

launchWaveFromPort Macro

launchWaveFromPort (position,polarization,freq,cutoff_freq,profile,grid_loc): This macro specifies a port(with profile, grid_loc and position) and then launches a wave from it.

If not applied to an entire face, upper and lower bounds (in grid cells) can be defined using the arguments below

launchWaveFromPort (position,polarization,freq,profile,direction,lx,ly,lz,ux,uy,uz):

launchWaveFromPort Macro Parameters

position: Face the port will be applied to (lowerX,lowerY,lowerZ,upperX,upperY or upperZ).

polarization (integer): Direction in which the wave is polarized. This is a coordinate system de-pendent quantity. In Cartesian coordinates 0=x, 1=y, 2=z.

freq: Frequency of the launched wave.

cutoff_freq: Cutoff frqenecy of the launched wave.

profile: Position of the wave launcher within the simulation environment.

grid_loc: Location of the port on the face determined by position.

lx: Lower bound in the x direction (meters).

ly: Lower bound in the y direction (meters).

222 Chapter 8. Macros

Page 227: VSim In Depth

VSim In Depth, Release 8.2.1

lz: Lower bound in the z direction (meters).

ux: Upper bound in the x direction (meters).

uy: Upper bound in the y direction (meters).

uz: Upper bound in the z direction (meters).

addWaveLauncher Macro

addWaveLauncher (name,polarization,profile,position): This macro specifies a boundary face to launch a wavedirectly into the electric field off of.

If the wave launcher is to be placed not on a boundary face, upper and lower bounds can be specified, using thecommand given below.

addWaveLauncher (name,polarization,profile,lx,ly,lz,ux,uy,uz):

addWaveLauncher Macro Parameters

name: Name of the wave launcher.

polarization (integer): Direction in which the wave is polarized. This is a coordinate system de-pendent quantity. In Cartesian coordinates 0=x, 1=y, 2=z.

profile: A function describing the form of the launched wave.

position: Face on whcih the wave launcher will be applied to (lowerX,lowerY,lowerZ,upperX,upperY,upperZ ).

lx: Lower bound in the x direction (meters).

ly: Lower bound in the y direction (meters).

lz: Lower bound in the z direction (meters).

ux: Upper bound in the x direction (meters).

uy: Upper bound in the y direction (meters).

uz: Upper bound in the z direction (meters).

addOpenBoundary Macro

addOpenBoundary (position): This macro creates an open boundary condition on the face specified by the posi-tion parameter.

addOpenBoundary Macro Parameters

position: Face the boundary condition will be applied to (lowerX,lowerY,lowerZ,upperX,upperY orupperZ).

addConductingBoundary Macro

addConductingBoundary (position): This macro creates an electrically conducting boundary condition on theface specified by the position parameter.

8.2. Macros present in Version 7 223

Page 228: VSim In Depth

VSim In Depth, Release 8.2.1

addConductingBoundary Macro Parameters

position: Face the boundary condition will be applied to (lowerX,lowerY,lowerZ,upperX,upperY orupperZ).

addMagneticBoundary Macro

addMagneticBoundary (position): This macro creates a magnetically conducting boundary condition on theface specified by the position parameter.

addMagnetic Boundary Macro Parameters

position: Face the boundary condition will be applied to (lowerX,lowerY,lowerZ,upperX,upperY orupperZ).

addMALBoundary Macro

addMALBoundary (position,thickness): This macro creates a MAL (Matched Absorbing Layer) boundary condi-tion on the face specified in position and thickness of the difference between its upper and lower bounds.

addMALBoundary Macro Parameters

position: Face the boundary condition will be applied to (lowerX,lowerY,lowerZ,upperX,upperY orupperZ).

thickness: The thickness of the MAL boundary (m).

8.3 Version 8 Macro Files and Macros

8.3.1 VSim.mac

This macro file can be imported to an input file with

$ import VSim

It is imported at the top of all simulation runs.

This macro file is available to all packages.

This macro file defines the finalize() macro, which writes out the blocks defined by accumulation variables. Thisfile also defines many of the global accumulation variables.

Public Macros

finalize(): Write out all the previously defined blocks in the correct order and with the correct nesting.

224 Chapter 8. Macros

Page 229: VSim In Depth

VSim In Depth, Release 8.2.1

8.3.2 VSimEm.mac

This macro file can be imported to an input file with

$ import VSimEm

It is imported by VSim if VPM_SIMULATION_TYPE is electromagnetic.

This macro file is available to all packages.

This macro file defines the finalizeUpdaters() macro, specific to electromagnetic simulations, and it alsodefines many macros for adding EM update steps.

Public Macros

writeMovingWindow(shiftPos, shiftSpd): Write a moving window in the X-Direction block to the toplevel of the .in file.

shiftPos: The fractional amount of the domain for the speed below to cross before shifting.

shiftSpd: The fraction of light speed to move the window by.

writeMovingWindow(shiftDir, shiftPos, shiftSpd): Write a moving window to the top level ofthe .in file with specifiable direction.

shiftDir: The capital character describing the (Cartesian) direction to shift the window. One of X,Y,Z.

shiftPos: The fractional amount of the domain for the speed below to cross before shifting.

shiftSpd: The fraction of light speed to move the window by.

addCurrentDistribution(name, j0, j1, j2, lc, uc): Add a current distribution into a slab.

name: The name of this current distribution.

j0: Function giving component 0 (x) of the current distribution.

j1: Function giving component 1 of the current distribution.

j2: Function giving component 2 of the current distribution.

lc: Lower limits of the coordinate slab over which to apply this current distribution

uc: Upper limits of the coordinate slab over which to apply this current distribution

addDipoleCurrentDistribution(name, comp, function, coordinate): Add a dipole currentat a coordinate.

name: The name of this dipole current distribution.

comp: The component of j that is being set.

function: Function that the component of j will be set to.

coordinate: The location for this dipole current.

finalizeUpdaters(): Create all of the updaters needed for an EM simulation. Writing them occurs in write-MultiField, which is called by finalize().

8.3. Version 8 Macro Files and Macros 225

Page 230: VSim In Depth

VSim In Depth, Release 8.2.1

8.3.3 VSimEs.mac

This macro file can be imported to an input file with

$ import VSimEs

It is imported by VSim if VPM_SIMULATION_TYPE is electrostatic.

This macro file is available to all packages.

This macro file defines the finalizeUpdaters() macro, specific to electrostatic simulations, and it also definesmany private macros for adding ES update steps.

Public Macros

finalizeUpdaters(): Add in all of the updaters needed for an ES simulation. Writing them occurs in write-MultiField, which is called by finalize().

8.3.4 beamemitters.mac

This macro file can be imported to an input file with

$ import beamemitters

It is imported by VSim whenever a simulation contains particles.

This macro file is available to all packages.

This macro file defines macros for adding beam emitters for particles to be emitted from.

Public Macros

addBeamEmitter(sourceName, owningSpecies, start, stop, vbar, vsig, fluxSetting, fluxOrCurrent, location):Add a particle emitter source block to the simulation. Velocity is given by the mean and standard deviation ofthe velocity distribution of the emitted particles. Current density is given by explicitly being set or by settingthe desired flux whereby a calculation is done later. Location of emission can be off a GridBoundary shape or aboundary of the simulation domain. Delegates to addSettableFluxEmitter(15 args).

sourceName: The name of the particle source block.

owningSpecies: The name of the emitted particle the source belongs to. Can be an electron, an ion, or aneutral particle.

start: The simulation time at which emission begins.

stop: The simulation time at which emission ends.

vbar: A three-vector of mean velocities.

vsig: A three-vector of rms velocities.

fluxSetting: A string used to determine whether to explicitly set the current density or to calculate it.

fluxOrCurrent: The function or numerical value used to set the current density or to calculate it.

location: The boundary plane of the simulation domain to emit off.

226 Chapter 8. Macros

Page 231: VSim In Depth

VSim In Depth, Release 8.2.1

addBeamEmitter(sourceName, owningSpecies, start, stop, vbar, vsig, fluxSetting, fluxOrCurrent, emOff, maskFunction, object):Add a particle emitter source block to the simulation. Velocity is given by the mean and standard deviation ofthe velocity distribution of the emitted particles. Current density is given by explicitly being set or by settingthe desired flux whereby a calculation is done later. Location of emission can be off a GridBoundary shape or aboundary of the simulation domain. Delegates to addSettableFluxEmitter(15 args).

sourceName: The name of the particle source block.

owningSpecies: The name of the emitted particle the source belongs to. Can be an electron, an ion, or aneutral particle.

start: The simulation time at which emission begins.

stop: The simulation time at which emission ends.

vbar: A three-vector of mean velocities.

vsig: A three-vector of rms velocities.

fluxSetting: A string used to determine whether to explicitly set the current density or to calculate it.

fluxOrCurrent: The function or numerical value used to set the current density or to calculate it.

emOff: The distance away from the emitting object to emit.

maskFunction: A function used to tailor the shape of emission off of the emitting object.

object: The shape object, or GridBoundary as it is called in vorpal, off of which to emit.

addBeamEmitter(sourceName, owningSpecies, start, stop, vbar, vsig, fluxSetting, fluxOrCurrent, coordinate, minValue, maxValue, location):Add a particle emitter source block to the simulation. Velocity is given by the mean and standard deviation ofthe velocity distribution of the emitted particles. Current density is given by explicitly being set or by settingthe desired flux whereby a calculation is done later. Location of emission can be off a GridBoundary shape or aboundary of the simulation domain. Delegates to addSettableFluxEmitter(15 args).

sourceName: The name of the particle source block.

owningSpecies: The name of the emitted particle the source belongs to. Can be an electron, an ion, or aneutral particle.

start: The simulation time at which emission begins.

stop: The simulation time at which emission ends.

vbar: A three-vector of mean velocities.

vsig: A three-vector of rms velocities.

fluxSetting: A string used to determine whether to explicitly set the current density or to calculate it.

fluxOrCurrent: The function or numerical value used to set the current density or to calculate it.

coordinate: The coordinate of the plane of emission. For a Z-Plane, an R-coordinate.

minValue: A coordinate defining the minimum spatial value for emission. For a Z-Plane a Z-coordinate.

maxValue: A coordinate defining the maximum spatial value for emission. For a Z-Plane a Z-coordinate.

location: The boundary plane of the simulation domain to emit off.

8.3.5 collisions.mac

This macro file can be imported to an input file with

8.3. Version 8 Macro Files and Macros 227

Page 232: VSim In Depth

VSim In Depth, Release 8.2.1

$ import collisions

It is imported by VSim whenever a simulation contains particles.

This macro file is available to all packages.

This macro file defines macros for adding collisions between particles and particles and between particles and fluidsinto a simulation.

To add collisions to your simulation with the collisions.mac macros involves 3 defining steps.

• Create the neutral gas using the fluids.mac macro addNeutralGas

• Specify the type of collisions (electrons or ions) by including a macro for either addElectronNeutralFluidColli-sions or addIonNeutralFluidCollisions

• Specify which types of collisions for each species where choices are

– electrons: Elastic, Excitation, Ionization

– ions: Charge Exchange, Momentum Exchange

Example

addNeutralGas(XeNeutralGas, Xe, initGasDen, 300., True, [zMin, rMin], [zMax, rMax])

addElectronNeutralFluidCollisions(elecNeutralColl, electrons, XeNeutralGas)

addElectronNeutralFluidIonizationCollision(elecIonization, elecNeutralColl, electrons,→˓ \

XePlus, isotropic, EvaluatedElectronDataLibrary, eedl.dat)

addElectronNeutralFluidElasticCollision(elecElastic, elecNeutralColl, isotropic, \EvaluatedElectronDataLibrary, eedl.dat)

addElectronNeutralFluidExcitationCollision(elecExcitation, elecNeutralColl, isotropic,→˓ \

EvaluatedElectronDataLibrary, eedl.dat)

Public Macros

addElectronNeutralFluidCollisions(name, impactElectrons, neutralGas): Add colli-sions between an electron species and a neutral background gas

name: The name of this collision process

impactElectrons: the name of the impacting electron species.

neutralGas: The name of the neutral background gas.

addIonNeutralFluidCollisions(name, impactIons, neutralGas): Add collisions between anion species and a neutral background gas

name: The name of this collision process

impactElectrons: the name of the impacting electron species.

neutralGas: The name of the neutral background gas.

228 Chapter 8. Macros

Page 233: VSim In Depth

VSim In Depth, Release 8.2.1

addElectronNeutralFluidElasticCollision(name, owningCollider, productDist, crossSectionType):Add elastic collision with built in cross sectioning

name: The name of this collision process

owningCollider: The collisions parent that defines the impact species and the neutral gas. The name usedfor the addElectronNeutralFluidCollisions macro.

productDist: The distribution of product velocities after collision. Choice of isotropic or VahediSurendra

crossSectionType: The cross section calculation method. Choice of userDefinedCrossSection or Evalu-atedElectronDataLibrary

addElectronNeutralFluidElasticCollision(name, owningCollider, productDist, crossSectionType, dataFile):Add elastic collision with file defined in cross sectioning

name: The name of this collision process

owningCollider: The collisions parent that defines the impact species and the neutral gas. The name usedfor the addElectronNeutralFluidCollisions macro.

productDist: The distribution of product velocities after collision. Choice of isotropic or VahediSurendra

crossSectionType: The cross section calculation method. Choice of userDefinedCrossSection or Evalu-atedElectronDataLibrary

dataFile: The file containing the cross section data.

addElectronNeutralFluidExcitationCollision(name, owningCollider, productDist, crossSectionType):Add excitation collision with built in cross sectioning

name: The name of this collision process

owningCollider: The collisions parent that defines the impact species and the neutral gas. The name usedfor the addElectronNeutralFluidCollisions macro.

productDist: The distribution of product velocities after collision. Choice of isotropic or VahediSurendra

crossSectionType: The cross section calculation method. Choice of userDefinedCrossSection or Evalu-atedElectronDataLibrary

addElectronNeutralFluidExcitationCollision(name, owningCollider, productDist, crossSectionType, dataFile):Add excitation collision with file defined in cross sectioning

name: The name of this collision process

owningCollider: The collisions parent that defines the impact species and the neutral gas. The name usedfor the addElectronNeutralFluidCollisions macro.

productDist: The distribution of product velocities after collision. Choice of isotropic or VahediSurendra

crossSectionType: The cross section calculation method. Choice of userDefinedCrossSection or Evalu-atedElectronDataLibrary

dataFile: The file containing the cross section data.

addElectronNeutralFluidIonizationCollision(name, owningCollider, productElectrons, productIons, productDist, crossSectionType):Add ionization collision with built in cross sectioning

name: The name of this collision process

owningCollider: The collisions parent that defines the impact species and the neutral gas. The name usedfor the addElectronNeutralFluidCollisions macro.

productElectrons: The name of the product electron species.

productIons: The name of the product ion species.

8.3. Version 8 Macro Files and Macros 229

Page 234: VSim In Depth

VSim In Depth, Release 8.2.1

productDist: The distribution of product velocities after collision. Choice of isotropic or VahediSurendra

crossSectionType: The cross section calculation method. Choice of builtIn, userDefinedCrossSection orEvaluatedElectronDataLibrary

addElectronNeutralFluidIonizationCollision(name, owningCollider, productElectrons, productIons, productDist, crossSectionType, dataFile):Add ionization collision with file defined in cross sectioning

name: The name of this collision process

owningCollider: The collisions parent that defines the impact species and the neutral gas. The name usedfor the addElectronNeutralFluidCollisions macro.

productElectrons: The name of the product electron species.

productIons: The name of the product ion species.

productDist: The distribution of product velocities after collision. Choice of isotropic or VahediSurendra

crossSectionType: The cross section calculation method. Choice of builtIn, userDefinedCrossSection orEvaluatedElectronDataLibrary

dataFile: The file containing the cross section data.

addIonNeutralFluidChargeExchangeCollision(name, owningCollider, productDist, crossSectionType):Add charge exchange collision with built in cross sectioning

name: The name of this collision process

owningCollider: The collisions parent that defines the impact species and the neutral gas. The name usedfor the addIonNeutralFluidCollisions macro.

productDist: The distribution of product velocities after collision. Choice of backward

crossSectionType: The cross section calculation method. Choice of builtIn or userDefinedCrossSection

addIonNeutralFluidChargeExchangeCollision(name, owningCollider, productDist, crossSectionType, dataFile):Add charge exchange collision with file defined in cross sectioning

name: The name of this collision process

owningCollider: The collisions parent that defines the impact species and the neutral gas. The name usedfor the addIonNeutralFluidCollisions macro.

productDist: The distribution of product velocities after collision. Choice of backward

crossSectionType: The cross section calculation method. Choice of builtIn or userDefinedCrossSection

dataFile: The file containing the cross section data.

addIonNeutralFluidMomentumExchangeCollision(name, owningCollider, productDist, crossSectionType):Add momentum exchange collision with built in cross sectioning

name: The name of this collision process

owningCollider: The collisions parent that defines the impact species and the neutral gas. The name usedfor the addIonNeutralFluidCollisions macro.

productDist: The distribution of product velocities after collision. Choice of backward

crossSectionType: The cross section calculation method. Choice of builtIn or userDefinedCrossSection

addIonNeutralFluidMomentumExchangeCollision(name, owningCollider, productDist, crossSectionType, dataFile):Add momentum exchange collision with file defined in cross sectioning

name: The name of this collision process

230 Chapter 8. Macros

Page 235: VSim In Depth

VSim In Depth, Release 8.2.1

owningCollider: The collisions parent that defines the impact species and the neutral gas. The name usedfor the addIonNeutralFluidCollisions macro.

productDist: The distribution of product velocities after collision. Choice of backward

crossSectionType: The cross section calculation method. Choice of builtIn or userDefinedCrossSection

dataFile: The file containing the cross section data.

8.3.6 esmatrix.mac

This macro file can be imported to an input file with

$ import esmatrix

It is imported by VSimEs.mac.

This macro file is available to all packages.

This macro file defines macros that set up the matrix for solving electrostatics. Includes setting up the bulk matrix andthe boundary conditions. Use by first adding all the needed boundary conditions. Then write the matrix, which willinsert those boundary conditions.

Default Accumulation Macros

addEsDirichletBC(name, value, location): Add a Dirichlet boundary condition using a simulationboundary location.

name: The name of the boundary condition block.

value: The voltage for this boundary condition.

location: The boundary condition location, one of lower/upper[X,Y,Z], e.g. for Cartesian coordinates.

addEsDirichletBC(name, value, lb, ub): Add a Dirichlet boundary condition using an index slab.

name: The name of the boundary condition block.

value: The voltage for this boundary condition.

lb: The lower bound indexes of the slab over which this boundary condition is applied.

ub: The upper bound indexes of the slab over which this boundary condition is applied.

addEsNeumannBC(name, value, location): Add a Neumann boundary condition using a simulationboundary location.

name: The name of the boundary condition block.

value: The value of the potential difference between two nodes.

location: The boundary condition location, one of lower/upper[X,Y,Z], e.g. for Cartesian coordinates.

addEsNeumannBC(name, value, direction, multiplier, lb, ub): Add a Neumann boundarycondition using an index slab.

name: The name of the boundary condition block.

value: The value of the potential difference between two nodes. (See multiplier).

direction: The direction of the potential difference. One of [0,1,2], corresponding to [X,Y,Z] in Cartesiancoordinate systems, e.g.

8.3. Version 8 Macro Files and Macros 231

Page 236: VSim In Depth

VSim In Depth, Release 8.2.1

multiplier: The multiplier for the potential difference. If this is positive, one takes the value one cell upminus the value at the node. If this is negative or zero, one takes the value at the node minus the value onecell down.

lb: The lower bound indexes of the slab over which this boundary condition is applied.

ub: The upper bound indexes of the slab over which this boundary condition is applied.

8.3.7 embcs.mac

This macro file can be imported to an input file with

$ import embcs

It is imported by VSimEM in all cases.

This macro file is available to all packages.

This macro file defines numerous different electromagnetic boundary conditions such as Ports, PortLauncers, PMLsand MALs, magnetic symmetries and electric symmetries.

Public Macros

addElectricBoundary(name, fieldName, location): Add an electric (PEC) boundary condition.

name: The name of the updater.

fieldName: Unused.

location: The location of the boundary condition, [lower/upper][X/Y/Z].

addMagneticBoundary(boundaryConditionName, fieldName, location): Add a magneticboundary condition.

boundaryConditionName: The name of the updater.

fieldName: Unused.

location: The location of the boundary condition, [lower/upper][X/Y/Z].

addOpenBoundary(boundaryConditionName, fieldName, location): Add an open boundary.

boundaryConditionName: The name of the updater.

fieldName: Unused.

location: The location of the boundary condition, [lower/upper][X/Y/Z].

addMalBoundary(boundaryConditionName, fieldName, location, malThickness): Add aMatched Absorbing Layer (MAL), a layer with increasing resistance out to the simulation boundary. Setsdefault pwr = 3.0, frac = 0.5, and malThickness=1.0

boundaryConditionName: The name of the updater.

fieldName: Name of the field. Determines updater and step names.

location: The location of the boundary condition, [lower/upper][X/Y/Z].

malThickness: Real valued thickness of MAL into sim domain, same units as the grid. There are macroguards on the tickness that restrict the MAL thickness to be no greater than 50% of the simulation domainand no thinner than 2 grid cells regardless of whether the user specify quantities greater/lesser than thesevalues.

232 Chapter 8. Macros

Page 237: VSim In Depth

VSim In Depth, Release 8.2.1

addBoundaryLauncher(boundaryConditionName, fieldName, xProfile, yProfile, zProfile, location):Add boundary launcher, formats the bounds

boundaryConditionName: The name of the updater.

fieldName: Name of the field. Determines updater and step names.

xProfile: The x component of the field

yProfile: The y component of the field

zProfile: The z component of the field

location: The location of the boundary condition, [lower/upper][X/Y/Z].

8.3.8 fluids.mac

This macro file can be imported to an input file with

$ import fluids

It is imported by VSim whenever a simulation contains particles.

This macro file is available to all packages.

This macro file defines macros for adding fluids that particles can collide off of.

Public Macros

addNeutralGas(name, gasKind, gasDensity, gasTemp, isvar, lc, uc): Add a fluid blockto the simulation. Adds to the fluid blocks accumulation variables and adds to accumulation variables forparameters like excitation and ionization thresholds for use in other blocks

name: the name of the fluid block.

gasKind: the kind of neutral gas. Typically the symbol for elemental fluids, e.g. Xe for xenon.

gasDensity: The function or numerical value for the initial density.

gasTemp: the neutral gas temperature.

isvar: whether the initial density is a spatially dependent expression, f(x,y,z), or a constant value (amplitude).

lc: the lower coordinates of the fluid location. Real array of length VPM_NDIM.

uc: the upper coordinates of the fluid location. Real array of length VPM_NDIM.

8.3.9 grids.mac

This macro file can be imported to an input file with

$ import grids

It is imported at the top of all simulation runs.

This macro file is available to all packages.

This macro file defines the variable for the grids. The grid is written at time of finalize.

8.3. Version 8 Macro Files and Macros 233

Page 238: VSim In Depth

VSim In Depth, Release 8.2.1

Public Macros

setGridData(nDim, coordSystem): Set the grid variables,

VPM_BGN0: The start of the grid in the first coordinate,

VPM_BGN1: The start of the grid in the second coordinate,

VPM_BGN2: The start of the grid in the third coordinate,

VPM_L0: The extent of the grid in the first coordinate,

VPM_L1: The extent of the grid in the second coordinate,

VPM_L2: The extent of the grid in the third coordinate,

VPM_N0: The number of cells in the first direction,

VPM_N1: The number of cells in the second direction,

VPM_N2: The number of cells in the third direction,

VPM_PERIODIC_DIRS: An array listing the coordinate directions in which one has periodic boundary condi-tions,

then calls setGridData(4 args) to set the coordinate-system dependent variables.

nDim: The dimensionality of the simulation.

coordSystem: The coordinate system. One of “UniformCartesian” or “Cylindrical”.

setGridData(nDim, coordSystem, numCells, lengths, startPositions): Set thecoordinate-system dependent grid variables, VPM_NDIM and VPM_GRID_TYPE, and sets the periodicdirections. For UniformCartesian, computes and sets

VPM_NX, VPM_NY, VPM_NZ, VPM_LX, VPM_LY, VPM_LZ, VPM_BGNX, VPM_BGNY, VPM_BGNZ,VPM_ENDX, VPM_ENDY, VPM_ENDZ, VPM_DX, VPM_DY, VPM_DZ, VPM_NXP1, VPM_NYP1,VPM_NZP1, VPM_NXM1, VPM_NYM1, VPM_NZM1, VPM_DXI, VPM_DYI, VPM_DZI, VPM_DL,VPM_DLI, depending on the dimensionality.

For Cylindrical, computes and sets VPM_NZ, VPM_NR, VPM_NPHI, VPM_LZ, VPM_LR, VPM_LPHI,VPM_BGNZ, VPM_BGNR, VPM_BGNPHI, VPM_ENDZ, VPM_ENDR, VPM_ENDPHI, VPM_DZ,VPM_DR, VPM_DPHI, VPM_NZP1, VPM_NRP1, VPM_NPHIP1, VPM_NZM1, VPM_NRM1,VPM_NPHIM1, VPM_DZI, VPM_DRI, VPM_DPHII, VPM_DL, VPM_DLI, depending on the dimen-sionality.

nDim: The dimensionality of the simulation.

coordSystem: The coordinate system. One of “UniformCartesian” or “Cylindrical”.

numCells: An integer array of length nDim indicating the number of cells in each direction.

lengths: A real-valued array of length nDim indicating the lengths of the simulation domain in each direc-tion.

startPositions: A real-valued array of length nDim indicating the start position of each direction. I.e. thecoordinate of the node with indices [0,0,0].

8.3.10 histories.mac

This macro file can be imported to an input file with

$ import histories

234 Chapter 8. Macros

Page 239: VSim In Depth

VSim In Depth, Release 8.2.1

It is imported by VSim.mac.

This macro file is available to all packages.

This macro file provides macros for all vorpal histories supported in this release. Histories pertain primarily to fieldsand particles.

Public Macros

addParticleMomentumHistory(name, speciesName): Add particle history block that records the mo-mentum of a particle species.

name: The name of the history block.

speciesName: The name of the species to be recorded.

addParticleAbsorberLog(name, absorberName, ptclQty, component): Add particle historyblock that records a specific quantity about particles absorbed by the given absorber.

name: The name of the history block.

absorberName: The name of the particle absorber at which to record.

ptclQty: The quantity to be recorded. Particle quantities include time, position, velocity, weight, energy, andcurrent.

component: The component of the particle quantity to record. Only position, velocity, and weight require acomponent.

addParticleAbsorberCurrentHistory(name, absorberName): Add particle history block thatrecords the current located at a particle absorber.

name: The name of the history block.

absorberName: The name of the particle absorber at which to record.

addParticleAbsorberEnergyHistory(name, absorberName): Add particle history block thatrecords the energy of particles located at a particle absorber.

name: The name of the history block.

absorberName: The name of the particle absorber at which to record.

addParticleEmitterCurrentHistory(name, emitterName): Add particle history block that recordsthe current located at a particle emitter.

name: The name of the history block.

emitterName: The name of the particle emitter at which to record.

addMacroParticleCountHistory(name, speciesName): Add particle history block that records thenumber of macro particles in a simulation.

name: The name of the history block.

speciesName: The name of the species to be recorded.

addPhysicalParticleCountHistory(name, speciesName): Add particle history block that recordsthe number of physical particles in a simulation.

name: The name of the history block.

speciesName: The name of the species to be recorded.

addParticleEnergyHistory(name, speciesName): Add particle history block that records energy of aparticle species.

8.3. Version 8 Macro Files and Macros 235

Page 240: VSim In Depth

VSim In Depth, Release 8.2.1

name: The name of the history block.

speciesName: The name of the species to be recorded.

addEMFieldEnergyHistory(name, region): Add field history block that records energy of the EM field.Can specify the entire simulation region or the region inside a user defined shape.

name: The name of the history block.

region: A string representing the region in which to record. Can either be the entire simulation domain or aregiondefined by an imported geometry or created through CSG.

addEMFieldEnergyHistory(name, lb, ub): Add field history block that records energy of the EM field.Can specify any region in the simulation domain.

name: The name of the history block.

lb: An integer three-vector. The lower bounds on which to record in grid indices.

ub: An integer three-vector. The upper bounds on which to record in grid indices.

addFieldEnergyAtPositionHistory(name, location, field): Add field history block thatrecords energy of the specified field. Records field energy at specific point in the simulation domain.

name: The name of the history block.

location: A real valued three-vector. The point at which to record.

field: The field which to record.

addElectricFieldEnergyHistory(name, simRgn): Add field history block that records energy of theelectric field inside the whole simulation domain.

name: The name of the history block.

simRgn: A string representing the entire simulation region.

addElectricFieldEnergyHistory(name, lb, ub): Add field history block that records energy of theelectric field. Can specify any region in the simulation domain.

name: The name of the history block.

lb: An integer three-vector. The lower bounds on which to record in grid indices.

ub: An integer three-vector. The upper bounds on which to record in grid indices.

addMagneticFieldEnergyHistory(name, simRgn): Add field history block that records energy of themagnetic field inside the whole simulation domain.

name: The name of the history block.

simRgn: A string representing the entire simulation region.

addMagneticFieldEnergyHistory(name, lb, ub): Add field history block that records energy of themagnetic field. Can specify any region in the simulation domain.

name: The name of the history block.

lb: An integer three-vector. The lower bounds on which to record, in grid indices.

ub: An integer three-vector. The upper bounds on which to record, in grid indices.

addPseudoPotentialHistory(name, refPoint, measPoint): Add history block that calculates thepseudo-potential difference, in volts, between the reference point and the measure point. See the pseudoPotentialdocumentation for details.

name: The name of the history block.

236 Chapter 8. Macros

Page 241: VSim In Depth

VSim In Depth, Release 8.2.1

refPoint: An integer three-vector. The grid indices of the reference point.

measPoint: An integer three-vector. The grid indices of the measurement point.

addBinaryCombinationHistory(name, coeff1, coeff2, op, history1, history2): Addhistory block that performs an element-wise binary operation on two other histories.

name: The name of the history block.

coeff1: A real valued coefficient for history1.

coeff2: A real valued coefficient for history2.

op: The operation to perform on the two histories.

history1: The name of the first history.

history2: The name of the second history.

addPoyntingHistory(name, lb, ub): Add history block that records the poynting flux on some planewithin the simulation domain.

name: The name of the history block.

lb: A real valued three-vector. The lower bounds on which to record, in coordinates.

coeff2: A real valued three-vector. The upper bounds on which to record, in coordinates.

addFarFieldHistory(name, timeDelay, duration, numTimePts, kirchRad, numPolarAng, numAzimAng, numLinInts, comp, kirchCenter, field):Add history block that records the far field radiation pattern of an EM source.

name: The name of the history block.

timeDelay: The simulation time at which to begin recording.

duration: The length of time during which the history records.

numTimePts: The number of sampling points on the time interval.

kirchRad: The radius of the Kirchhoff sphere.

numPolarAng: The number of polar angles represented on the Kirchhoff sphere.

numAzimAng: The number of azimuthal angles represented on the Kirchhoff sphere.

numLinInts: The number of integration segments around the Kirchhoff sphere.

kirchCenter: The center of the Kirchhoff sphere.

8.3.11 matrices.mac

This macro file can be imported to an input file with

$ import matrices

It is imported by VSimEs.mac.

This macro file is available to all packages.

This macro file defines macros for matrices. None of the macros are considered public, i.e., with stable APIs.

8.3. Version 8 Macro Files and Macros 237

Page 242: VSim In Depth

VSim In Depth, Release 8.2.1

Macros

StencilElementMacro(name, value, minDim, offset, rowFldIndx, colFldIndx): Insert aconstant-value matrices StencilElement.

name: The name to give the stencil element.

value: The value of the stencil element.

minDim: The minimum dimensionality to apply this stencil element.

offset: The offset (in index space) of the column cell from the row cel.

rowFldIndx: The index in the matrices for the row. This corresponds to the writefield for multiply, to thereadfield for solve.

colFldIndx: The index in the matrices for the column. This corresponds to the readfield for multiply, to thewritefield for solve.

STFuncStencilElementMacro(name, value, minDim, cellOffset, funcOffset, rowFldIndx, colFldIndx):Insert a function-value matrices StencilElement.

name: The name to give the stencil element.

value: The value of the stencil element.

minDim: The minimum dimensionality to apply this stencil element.

cellOffset: The offset (in index space) of the column cell from the row cel.

funcOffset: The offset (in real space, as a multiple of the grid spacing) of the function evaluation pointfrom the row cell.

rowFldIndx: The index in the matrices for the row. This corresponds to the writefield for multiply, to thereadfield for solve.

colFldIndx: The index in the matrices for the column. This corresponds to the readfield for multiply, to thewritefield for solve.

CoordProdSTFuncStencilElementMacro(name, value, minDim, cellOffset, funcOffset, gridDir, gridOffset, rowFldIndx, colFldIndx):insert a function-value matrices StencilElement in coordProd grid.

name: The name to give the stencil element.

value: The value of the stencil element.

minDim: The minimum dimensionality to apply this stencil element.

cellOffset: The offset (in index space) of the column cell from the row cel.

funcOffset: The offset (in real space, as a multiple of the grid spacing) of the function evaluation pointfrom the row cell.

gridDir: The direction in which differencing is being done for the stencil. Determines which grid spacingand face area to use.

gridOffset: The offset (in index space) from the row cell at which the grid spacing and face area are taken.

rowFldIndx: The index in the matrices for the row. This corresponds to the writefield for multiply, to thereadfield for solve.

colFldIndx: The index in the matrices for the column. This corresponds to the readfield for multiply, to thewritefield for solve.

238 Chapter 8. Macros

Page 243: VSim In Depth

VSim In Depth, Release 8.2.1

8.3.12 multifields.mac

This macro file can be imported to an input file with

$ import multifields

It is imported by VSim in all cases (electromagnetic and electrostatic).

This macro file is available to all packages.

This macro file contains many macros which add initial conditions to fields. It also contains macros to setup commonoperations with fields such as needed to make nodal fields, add applied (external) magnetic fields, copy perimieterfields, and perform binary operations with fields. A master macro, writeMultiField(), writes the <MultiField>block with all of the specified field operations.

Public Macros

addInitialCondition(fieldName, numComponents, comp0, comp1, comp2): Add initial con-ditions to field blocks.

fieldName: The name of the field into which the initial condition block is written. Determines the name ofthe InitialCondition block.

numComponents: The number of components in the initial condition.

comp0: Expression (or None) for the component 0 of the initial condition.

comp1: Expression (or None) for the component 1 of the initial condition.

comp2: Expression (or None) for the component 2 of the initial condition.

addInitialCondition(fieldName, numComponents, comp0, comp1, comp2, lb, ub): Addinitial conditions to field blocks.

fieldName: The name of the field into which the initial condition block is written. Determines the name ofthe InitialCondition block.

numComponents: The number of components in the initial condition.

comp0: Expression (or None) for the component 0 of the initial condition.

comp1: Expression (or None) for the component 1 of the initial condition.

comp2: Expression (or None) for the component 2 of the initial condition.

lb: The grid index (integer) lowerBounds of the initial condition.

ub: The grid index (integer) upperBounds of the initial condition.

addFieldInitialCondition(fieldName, component, function): Add an initial update step forinitial conditions.

fieldName: fieldName The name of the field being initialized.

component: The (integer) component of the field to initialize.

function: The function to which the field will be initialized to.

8.3.13 particles.mac

This macro file can be imported to an input file with

8.3. Version 8 Macro Files and Macros 239

Page 244: VSim In Depth

VSim In Depth, Release 8.2.1

$ import particles

It is imported by VSim if VPM_INCLUDE_PARTICLES is true.

This macro file is available to all packages.

This macro file defines the finalizeParticles() macro, specific to particle simulations. It contains the macrosfor defining particle species. It also contains macros for <ParticleSources> whcih load the particles into the simulation,for <ParticleSinks> which remove particles from a simulation.

Public Macros

addParticleSpecies(speciesName, kind, charge, mass, nominalDensity, weighting, weightSetting, ppmorc):Add a particle species to a simulation by adding its data to the accumulation variables. Other accumulationvariables, like those for sources and sinks, are added to by the other “add” methods. finalizeParticles() writesout the species with their sources and sinks.

speciesName: The name of the particle species.

kind: The kind of species, e.g. relBoris, relBorisCyl, etc.

charge: The charge of a physical particle of the species, in Coulombs.

mass: The mass of a physcial particle of the species, in Kg.

nominalDensity: A convenient (anticipated) density for the species, in 1/meters^3. Together with nomPt-clsPerCell, it can be used to set the wieght of a constantWeight macroparticles, or the normalization ofvariableWeight macroparticles.

weighting: The weighting for this species, either “constantWeights” or “variableWeights”.

weightSetting: How the weight is set, either explicitlySetWeights, or computedWeights from nomi-nalDensity.

ppmorc: For computedWeights, the number of macro particles in a cell, when the density in that cell is equalto nominal density. For explicitlySetWeights, the number of physical particles represented by one macroparticle.

addParticleSpeciesLoader(sourceName, owningSpecies, initOrRepeat, denTyp, denFunc, posGenKind, vbar, vsig, lb, ub):Add a particle loader to a particle species given the mean and standard deviation of the velocity distribution ofthe loaded particles. Loading is only on initialization.

sourceName: The name of the particle loader.

owningSpecies: The name of the species to be loaded.

initOrRepeat: A string denoting whether the loading is initialize only or to repeat.

denTyp: Either physics load density or relative (to nominal) load density.

denFunc: The function to use for loading.

posGenKind: The kind of position generator (grid, bit-rev, ...).

vbar: A three-vector of mean velocities.

vsig: A three-vector of rms velocities.

lb: An NDIM vector of loower coordinates.

ub: An NDIM vector of upper coordinates.

240 Chapter 8. Macros

Page 245: VSim In Depth

VSim In Depth, Release 8.2.1

addParticleSpeciesLoader(sourceName, owningSpecies, initOrRepeat, tmin, tmax, denTyp, denFunc, posGenKind, vbar, vsig, lb, ub):Add a particle loader to a particle species given the mean and standard deviation of the velocity distribution ofthe loaded particles. Loading is only on initialization. Delegates to addParticleSpeciesLoader(14 args).

sourceName: The name of the particle loader.

owningSpecies: The name of the species to be loaded.

initOrRepeat: A string denoting whether the loading is initialize only or to repeat.

tmin: Tthe time to start loading.

tmax: The time to stop loading (inclusive).

denTyp: Either physics load density or relative (to nominal) load density.

denFunc: The function to use for loading.

posGenKind: The kind of position generator (grid, bit-rev, ...).

vbar: A three-vector of mean velocities.

vsig: A three-vector of rms velocities.

lb: An NDIM vector of loower coordinates.

ub: An NDIM vector of upper coordinates.

addParticleSpeciesSink(sinkName, owningSpecies, sinkKind, volType, lb, ub): Adda particle species sink to a particle species given the lower and upper bounds.

sinkName: The name of the particle sink.

owningSpecies: The name of the species that contains this source block.

sinkKind: The kind of sink. E.g. absAndSav, absorber, specularBndry, absAndSavCutCell.

volType: The type of volume, either slab or location.

lb: The lower bounds. An integer array of length VPM_NDIM.

ub: The upper bounds. An integer array of length VPM_NDIM.

addParticleSpeciesSink(sinkName, owningSpecies, sinkKind, location): Add a particlespecies sink to a particle species given the location.

sinkName: The name of the particle sink.

owningSpecies: The name of the species that contains this source block.

sinkKind: The kind of sink. E.g. absAndSav, absorber, specularBndry, absAndSavCutCell.

location: location The location of the boundary condition, one of [lower|upper][X|Y|Z].

addParticleSpeciesSink(sinkName, owningSpecies, sinkKind, volType, lb, ub, location):Add a particle species sink to a particle species. Either location or lb and ub should be None, as they aremutually exclusive. Done by adding to the string arrays describing the sink.

sinkName: The name of the particle sink.

owningSpecies: The name of the species that contains this source block.

sinkKind: The kind of sink. E.g. absAndSav, absorber, specularBndry, absAndSavCutCell.

volType: The type of volume, either slab or location.

lb: The lower bounds. An integer array of length VPM_NDIM.

ub: The upper bounds. An integer array of length VPM_NDIM.

8.3. Version 8 Macro Files and Macros 241

Page 246: VSim In Depth

VSim In Depth, Release 8.2.1

location: location The location of the boundary condition, one of [lower|upper][X|Y|Z].

finalizeParticles(): Writing the particle Species blocks. Inserts Sinks and Sources (loaders and emitters)into the block. Writes depositor fields if electrostatic simulation.

8.3.14 secondemits.mac

This macro file can be imported to an input file with

$ import secondemits

It is imported by VSim whenever a simulation contains particles.

This macro file is available to all packages.

This macro file defines macros for adding secondary emitters for the various kinds of secondary emission supportedby vorpal.

Public Macros

addSecondaryElectronEmitter(secElecSpeciesName, secElecElectronSpeciesName, start, stop, material, suppressEnergy, secElecParticleSinkName):Add a secondary electron particle source block to the simulation. Emission is from a primary particle source’sabsorber which can either be a shape (imported or created through CSG) or a boundary of the simulationdomain. Emission takes into account material properties. Delegates to addSecondaryElectrons(10 args).

secElecSpeciesName: The name of the secondary electron particle source block.

secElecElectronSpeciesName: The name of the emitted electron species.

start: The simulation time at which emission begins.

stop: The simulation time at which emission ends.

material: A material that determines secondary electron yield. Can be either “copper” or “stainless”.

suppressEnergy: A real number, units eV, denoting the suppressing energy of the local electric field. If thelocal field is of sign that would immediately push the electron back into the surface, then emission doesnot occur. If emission is desired regardless than this number is set to a very large number. Default is 1e20.

secElecParticleSinkName: The name of the particle sink that the secondary electrons are to be emittedfrom. Must be a Boundary Absorb and Save or a Cut Cell Absorb and Save.

addInteriorSecondaryElectronEmitter(secElecSpeciesName, secElecElectronSpeciesName, start, stop, material, suppressEnergy, emissionAxis, emissionDir, emissionCoord, secElecParticleSinkName):Add a secondary electron particle source block to the simulation. Emission is from a primary particle source’sabsorber which is interior to the simulation domain. Emission takes into account material properties. Emissiondirection and offset can be defined as desired. Delegates to addSecondaryElectrons(10 args).

secElecSpeciesName: The name of the secondary electron particle source block.

secElecElectronSpeciesName: The name of the emitted electron species.

start: The simulation time at which emission begins.

stop: The simulation time at which emission ends.

material: A material that determines secondary electron yield. Can be either “copper” or “stainless”.

suppressEnergy: A real number, units eV, denoting the suppressing energy of the local electric field. If thelocal field is of sign that would immediately push the electron back into the surface, then emission doesnot occur. If emission is desired regardless than this number is set to a very large number. Default is 1e20.

emissionAxis: An integer that defines the axis of emission (e.g. x,y, or z).

242 Chapter 8. Macros

Page 247: VSim In Depth

VSim In Depth, Release 8.2.1

emissionDir: A string: “positive” or “negative”. Defines which direction for the secondary electrons totravel after emission.

emissionCoord: A real valued coordinate that defines the emission offset, or the distance away from theabsorber to emit.

secElecParticleSinkName: The name of the particle sink that the secondary electrons are to be emittedfrom. Must be a Interior Absorb and Save.

addSimpleSecondaryElectronEmitter(simpleSecSpeciesName, simpleSecElectronSpeciesName, start, stop, suppressEnergy, emittedEnergy, SEY, simpleSecParticleSinkName):Add a secondary electron particle source block to the simulation. The secondary electron is of the same speciesas the primary (absorbed) electron. Emission is from a primary electron’s absorber which can either be a shape(imported or created through CSG) or a boundary of the simulation domain. The emitted electron’s energy canbe specified along with the secondary electron yield.

simpleSecSpeciesName: The name of the secondary electron particle source block.

simpleSecElectronSpeciesName: The name of the emitted electron species.

start: The simulation time at which emission begins.

stop: The simulation time at which emission ends.

suppressEnergy: A real number, units eV, denoting the suppressing energy of the local electric field. If thelocal field is of sign that would immediately push the electron back into the surface, then emission doesnot occur. If emission is desired regardless than this number is set to a very large number. Default is 1e20.

emittedEnergy: A real number denoting the energy, in Joules, of the emitted electrons.

SEY: A function of energy, in eV, that determines the secondary electron yield curve.

simpleSecParticleSinkName: The name of the particle sink that the secondary electrons are to be emit-ted from. Must be a Boundary Absorb and Save or a Cut Cell Absorb and Save.

addConstantProbabilitySecondaryElectronEmitter(constProbSecSpeciesName, constProbSecElectronSpeciesName, start, stop, emissionProb, constProbSecParticleSinkName):Add a secondary electron particle source block to the simulation. Emission is from the primary species’ ab-sorber which can either be a shape (imported or created through CSG) or a boundary of the simulation domain.The probability for emission can be explicitly set.

constProbSecSpeciesName: The name of the secondary electron particle source block.

constProbSecElectronSpeciesName: The name of the emitted electron species.

start: The simulation time at which emission begins.

stop: The simulation time at which emission ends.

emittedProb: A real valued number on [0.0, 1.0] denoting the probability of emitting a secondary electron.

constProbSecParticleSinkName: The name of the particle sink that the secondary electrons are to beemitted from. Must be a Boundary Absorb and Save or a Cut Cell Absorb and Save.

addSputterEmitter(sputterSpeciesName, sputterElectronSpeciesName, start, stop, sputterEmittedSpeciesType, vsig, sputterParticleSinkName):Add a secondary neutral particle source block to the simulation. Emission is from the primary species’ absorberwhich can either be a shape (imported or created through CSG) or a boundary of the simulation domain. Thetype of atom to be sputtered can be selected along with the standard deviation of the velocity of the emittedparticles. Delegates to addSputterer(10 args).

sputterSpeciesName: The name of the secondary electron particle source block.

sputterElectronSpeciesName: The name of the emitted electron species.

start: The simulation time at which emission begins.

stop: The simulation time at which emission ends.

8.3. Version 8 Macro Files and Macros 243

Page 248: VSim In Depth

VSim In Depth, Release 8.2.1

sputterEmittedSpeciesType: The type of atom that is to be sputtered. See the sputter emitter docu-mentation for a list of valid types.

vsig: A three-vector of rms velocities.

sputterParticleSinkName: The name of the particle sink that the secondary particles are to be emittedfrom. Must be a Boundary Absorb and Save or a Cut Cell Absorb and Save.

addSputterEmitter(sputterSpeciesName, sputterElectronSpeciesName, start, stop, sputterEmittedSpeciesType, vsig, emissionAxis, emissionDir, emissionCoord, sputterParticleSinkName):Add a secondary neutral particle source block to the simulation. Emission is from the primary species’ absorberwhich can either be a shape (imported or created through CSG) or a boundary of the simulation domain. Thetype of atom to be sputtered can be selected along with the standard deviation of the velocity of the emittedparticles. Emission direction and offset can be defined as desired. Delegates to addSputterer(10 args).

sputterSpeciesName: The name of the secondary electron particle source block.

sputterElectronSpeciesName: The name of the emitted electron species.

start: The simulation time at which emission begins.

stop: The simulation time at which emission ends.

sputterEmittedSpeciesType: The type of atom that is to be sputtered. See the sputter emitter docu-mentation for a list of valid types.

vsig: A three-vector of rms velocities.

emissionAxis: An integer that defines the axis of emission (e.g. x,y, or z).

emissionDir: A string: “positive” or “negative”. Defines which direction for the secondary electrons totravel after emission.

emissionCoord: A real valued coordinate that defines the emission offset, or the distance away from theabsorber to emit.

sputterParticleSinkName: The name of the particle sink that the secondary particles are to be emittedfrom. Must be a Boundary Absorb and Save or a Cut Cell Absorb and Save.

8.3.15 shapes.mac

This macro file can be imported to an input file with

$ import shapes

It is always imported by VSim at the top level.

This macro file is available to all packages.

This macro file defines the macros for adding shapes of different materials.

Public Macros

addShape(cadBoundaryName, cadFileName, material): Add a shape by writing the GridBoundaryblock to the shapes accumulation variable. If PEC, set VPM_CONDUCTING_GRID_BOUNDARY_NAME to thisname Else If dielectric, add to the dielectric shapes, etc.

cadBoundaryName: The name of the GridBoundary.

cadFileName: The name of the (stl) file that contains the geometry.

material: The name of the material that the boundary is made of

244 Chapter 8. Macros

Page 249: VSim In Depth

VSim In Depth, Release 8.2.1

addConductor(materialName, resistance): Add a conducting material.

materialName: The name of the material.

resistance: The resistance of the material.

addDielectric(materialName, relativePermittivity, conductivity): Add a dielectric ma-terial.

materialName: The name of the material.

relativePermittivity: The relative permittivity of the material.

conductivity: The conductivity of the dielectric object.

8.3.16 solvers.mac

This macro file can be imported to an input file with

$ import solvers

It is imported by VSimEs.mac.

This macro file is available to all packages.

This macro file provides macros for Poisson solvers, which are described below.

Default Accumulation Macros

addBaseSolver(name, krySize, orthog): Add the base solver block for an iterative solver to the accu-mulation variable, VPM_MATRIX_SOLVER, which will be put into the simulation.

name: Name for the updater.

krySize: The size of the Krylov subspace. For gmres only.

orthog: The orthogonality type for the Krylov subspace. For gmres only.

8.3.17 timing.mac

This macro file can be imported to an input file with

$ import timing

It is imported by VSim.mac.

This macro file is available to all packages.

This macro file defines time-related parameters and makes them global variables.

Public Macros

setTimingData(): In the typical use case, VPM_DT, VPM_NSTEPS, VPM_DUMP_PERIOD, VPM_DMFRAC,and VPM_CFL_NUMBER are set before entry. This macro then computes VPM_SIMULATION_TIME, andVPM_NUM_DUMPS. VPM_DT is respected if not zero. Otherwise it is computed from the VPM_CFL_NUMBERand the minimum CFL time steps from electromagnetics (if an electromagnetic simulation) and (if thereare particles present) the plasma frequency and the thermal electron cell crossing time computed fromVPM_MAX_ELECTRON_DENSITY and VPM_MAX_ELECTRON_TEMP_EV.

8.3. Version 8 Macro Files and Macros 245

Page 250: VSim In Depth

VSim In Depth, Release 8.2.1

8.3.18 vputilities.mac

This macro file can be imported to an input file with

$ import vputilities

It is imported by VSim.mac.

This macro file is available to all packages.

This macro file defines vsim-specific utility macros.

Public Macros

writeIndicesFromCoords(coordBounds): Convert coordinates to the corresponding indices.

coordBounds: The coordinates to be converted. A float array of length VPM_NDIM.

write1CellVolume(p, outwardNormal, dl0, dl1, dl2, l0, l1, l2, st0, st1, st2):Create a 1-cell slab from in (x,y,z) tuple and a direction outwardNormal. It is a tuple that points in the directionof the outward normal to the surface.

p: A value that gives the position to place the slab

outwardNormal: Array of integers specifying the outward normals.

dl0: Cell length in the zeroth direction, e.g. VPM_DX.

dl1: Cell length in the first direction, e.g. VPM_DY.

dl2: Cell length in the second direction, e.g. VPM_DZ.

l0: Length of the domain in the zeroth direction, e.g. VPM_LX.

l1: Length of the domain in the first direction, e.g. VPM_LY.

l2: Length of the domain in the second direction, e.g. VPM_LZ.

st0: Starting point in the zeroth direction, e.g. VPM_BGNX.

st1: Starting point in the first direction, e.g. VPM_BGNY.

st2: Starting point in the second direction, e.g. VPM_BGNZ.

getBoundaryOffsets(location): Apply offsets to our bounds if a boundary condition has already been setto an orthogonal face.

location: The boundary location, one of lower/upper[X,Y,Z].

246 Chapter 8. Macros

Page 251: VSim In Depth

CHAPTER

NINE

ANALYSIS WINDOW

9.1 Overview

It is possible to run post processing analysis scripts within the VSimComposer environment. These scripts can processdata generated in a simulation and write that data to a .h5 file that can then be visualized like any other simulation data.

Custom post processing scripts can also be created by a user. This is covered in more detail in Creating your ownAnalysis Script

First we will see an analysis script in action by looking at the two stream example.

9.1.1 Running the two stream example to illustrate analysis scripts

• Select the New → From Example... menu item in the File menu.

• In the resulting Examples window expand the VSim for Basic Physics option.

• Expand the Textbook Examples (Text-based setup) option.

• Select Two-Stream Instability and press the Choose button.

• In the resulting dialog, create a New Folder if desired, and press the Save button to create a copy of this examplein your run area.

• This will open the Two-Stream Instability example, which must then have it’s primary variables modified.

• Click on the VBAR ( Average Velocity of Electron Beams [m/s]) and reduce it to 7.78e3. This is necessarybecause we will be converting the simulation to two dimensions, and if not slown down, the simulation canbecome unstable.

• Click on the PPC (Particles Per Cell) parameter and reduce it to 10. This step isn’t necessary, but in the interestsof having a short simulation time it is helpful.

• Click on the NDIM parameter and switch it to 2. This will set the simulation to run in two dimensions.

• Next click on the Validate button in the top right hand corner of the screen to validate the simulation with alteredparameters.

9.1.2 Analyzing the Data in the Two Stream Example

Proceed to the Run Window and run the simulation and click the Run button.

Once the simulation run has completed, click on the Analyze tab located below the Run tab on the left hand side of thescreen.

247

Page 252: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 9.1: Setup Window with Parameters Modified

• In the Analysis Control Pane click on the <Choose an analyzer> drop down menu. This will bring up theanalysis script for the example.

• For this example we will select computePtclNumDensity.py

• In the Analysis Results pane under the help tab instructions as to what variables have to be given by the user willappear.

• For this particular script, the only two variables are the simulationName and the speciesName. For simula-tionName, give it the name of the simulation, in our case twoStreamT. The speciesName parameter is eitherelectrons0 or electrons1, the two species of electrons in this simulation.

Then click the Run Button located at the bottom of the Control Pane.

9.1.3 Visualizing the Data Generated from an Analysis Script

The data generated from the execution of an analysis script will be stored as a .vsh5 file and is visualizable underneaththe Visualize tab.

• Switch the Data View to Field Analysis

• Select electrons0Density for the Field

• Set the linout to be horizontal

• set the Layout to be stacked

Here you can see the density of electrons0 species evolving through time. Our data is choppy because we did not runwith many particles.

248 Chapter 9. Analysis Window

Page 253: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 9.2: Analysis Window with Parameters Filled In

Fig. 9.3: Analysis Window Successful Run

9.1. Overview 249

Page 254: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 9.4: Visualization of the analysis data

9.2 Selecting an Analysis Script

There are 3 different ways to select an analysis script for your simulation.

• Set a default analysis script in your .pre file

• Select a pre-defined (installed with VSim) analysis script to use one time

• Import your own analysis script

9.2.1 Set a default analysis script in your .pre file

In order to make a particular analysis script always available to a particular input file, the analysis script must bespecified in the XSim block of the input file. For example, the analyzers in the default two stream example is:

<XSim twoStream>shortDescription = "Two-Stream Instability"description = "Two oppositely propagating electron beams, with periodic

boundaries and a sinusoidal variation in their velocities."longDescription = "Two oppositely propagating electron beams, with

periodic boundaries and a sinusoidal variation in theirvelocities. A collision-less plasma instability arisingfrom small charge imbalances can be seen in plots of theparticle phase space."

image = "twoStream.png"thumbnail = "twoStreamTn.png"analyzers = [computePtclNumDensity.py]canChangeDt = true

250 Chapter 9. Analysis Window

Page 255: VSim In Depth

VSim In Depth, Release 8.2.1

canChangeNdim = false</XSim>

9.2.2 Select a pre-defined (installed with VSim) analysis script to use one time

VSimComposer allows the user to also select a pre-defined (installed with VSim) analysis script from the AnalysisWindow.

Click on the box Set Allowed Analyzers in the Analysis Window. Here you can check any number of pre-definedanalysis scripts for use in your simulation.

Once you have checked the desired scripts, click OK and now these scripts will be available from the Active Analyzerdrop down list.

9.2.3 Import your own analysis script

If you have created your own analysis script, you can import it for use in VSimCompoesr by clicking on the buttonBrowse for custom analyzer. Navigate to your analysis script and then click Open.

These scripts will now be available from the Active Analyzer drop down list.

Fig. 9.5: Select a Custom Script

9.2. Selecting an Analysis Script 251

Page 256: VSim In Depth

VSim In Depth, Release 8.2.1

9.3 Creating your own Analysis Script

You may eventually find that you would like to process data from a simulation run with a script that is not pre-definedand installed with VSimComposer.

Note: Analysis scripts need to be written in Python

Given below are the key parts to enable easy compatibility with VSimComposer.

First part: Describe the inputs and outputs in a python literal string at the beginning of the file. The line Output:is explictly parsed, so please include that exactly as shown below. For example:

"""This analysis script, sampleScript.py, compute the flibbertygibbetbased on Vorpal's history file

Arguments:SIMULATIONNAME: The Name of this simulation.HISTORYNAME: The name of the history dataset used in the calibration run.FREQUENCY: The frequency at which *history* will be analyzed.OUTPUTFILENAME: [Optional] Name of the output vsh5 file that the transformed timeseries will be written in to. Default is SIMULATIONNAME_timeSeriesAmplitude.vsh5.OVERWRITE: Whether or not a dataset or group that already exists in the outputfile should be overwritten by this script if the names are the same.Default is False.

Output:

The variable specifed in variableName will then be available for use inthe script. Strictly speaking the fourth step only needs to include theline " variable = options.variableName" but it is generally consideredgood practice by Tech-X developers to include errors if a parameter isnot specified."""

Second part: import the standard modules used for analysis scripts:

import VsHdf5import TxPyUtils

Third part: use TxPyUtils to handle the input to the analysis script and interaction with VSimComposer. Please seeTxPyUtils User’s Guide:

options = []options.append(('-s','--simulationName','Base simulation name, i.e., the input ' +

'file name without extension.', 'string', None, True))options.append(('-H','--historyName', 'Name of farfield history dataset.', 'string',→˓None, True))options.append(('-q','--FREQ', 'The Frequncy', 'float', None, True))options.append(('-s','--outputFileName','Name of the output vsh5 file.', 'string',→˓None, False))

ops = TxPyUtils.TxOptParse(desc=description, ops=options)

Fourth part: read the variables in to your script. Please see TxPyUtils User’s Guide:

252 Chapter 9. Analysis Window

Page 257: VSim In Depth

VSim In Depth, Release 8.2.1

baseName = ops['simulationName']histName = ops['historyName']frequency = float(ops['FREQ'])output = ops['outputFileName']overwrite = ops['overwrite']

Fifth part: your analysis script. Please see VsHdf5 User’s Guide:

This is where you put your python analysis code.We recommend using VsHdf5.py to make the reading of the vorpal output easier.

Sixth part: write the output to a file for viewing in VSimComposer. Please see VsHdf5 User’s Guide:

dataset3 = baseName + '_' + history + '.vsh5'mesh = VsHdf5.StructuredMesh('farFieldMesh')mesh.writeMesh(dataset3, data=points, overwrite=overwrite)pointDataHist = VsHdf5.History(history)pointDataHist.assignDataset(pointData)pointDataHist.assignAttribute('vsCentering', 'nodal')pointDataHist.writeHistory(dataset3, mesh='farFieldMesh', overwrite=overwrite)

9.4 VSim Pre-Defined Analysis Scripts

9.4.1 List of pre-defined Analysis Scripts

Vsim 8 provides a number of scripts to simplify postprocessing the quantities you need from the quantities VSimcomputes for you.

These files are located in the same directory as the vorpal executable, and they may be used either within VSimCom-poser’s analysis tab python environment or directly on the command line. We have chosen to include even some scriptswhich are not tested nightly, as they demonstrate how to do make the most of the capabilities available. For those at(beta) level, you may find the code is not set up handle certain input files you would expect it to handle, nor to provideerrors for all scenarios in which it might be used. When you choose to use these it is recommended that you assess theresults cautiously, and in coordination with the code for the analyzer.

• addPtclComponentKEeV.py – Compute Particle Kinetic Energy in eV

• annotateFieldOnLine.py – Label fieldOnLine diagnostics (beta)

• annotateSpeciesAbsPtclData2.py – Annotate and combine particles in speciesAbsPtclData2 history (beta)

• calculateEmittance.py – Calculate Emittance

• calculateFieldMaxAmplitude.py – Check field maximum as a function of time (beta)

• computeBeam2ModeCoupling.py – Compute the Beam to Mode Coupling

• computeCumulativeSumHistory.py – Sum a history (beta)

• computeDebyeLength.py – Computing the Debye Length (cylindrical only) (beta)

• computeFarFieldRadiation.py – Far Field Analysis

• computeFieldCrossProduct.py – Compute cross product between two fields (beta)

• computeInverseQ.py – Compute Inverse Q Analysis

• computeLineIntegral.py – Compute the line integral of an electric field (beta)

9.4. VSim Pre-Defined Analysis Scripts 253

Page 258: VSim In Depth

VSim In Depth, Release 8.2.1

• computePtclLimits.py – Locate particles with highest or lowest values along coordinates (beta)

• computePtclNumDensity.py – Particle Number Density Analysis

• computeS11Parameters.py – S11 Parameter Script

• computeSpectrogram.py – Make spectrogram (beta)

• computeSurfaceFlux.py – Compute the flux integral of a magnetic field (beta)

• computeTimeSeriesAmplitude.py – Time Series Amplitude Analysis

• computeTimeSeriesFrequency.py – Time Series Frequency Analysis

• convertFieldComponentCartToCylX.py – Cartesian Field Components to Cylindrical Components Script (x-axis)

• convertFieldComponentCartToCylZ.py – Cartesian Field Components to Cylindrical Components Script (z-axis)

• convertPtclComponentsCartToCylX.py – Generate cylindrical particle coordinates in cylindrical coords fromcarteisan simulation (beta)

• convertPtclComponentsCartToCylZ.py – Generate cylindrical particle coordinates in cylindrical coords fromcarteisan simulation (beta)

• createMissingPtclsDumps.py – Add small particle datasets to synchronize visualization (beta)

• createParticleTracks.py – Make files which track particle trajectories (beta)

• extractModes.py –Extract Modes Analysis Script

• performLowPassFilter.py – Perform Low Pass Filter

• performTwoHistoryArithmetic.py – Perform Mathematical Operations on two histories (beta)

• subselectparticles.py – Subselect Particles (beta)

9.4.2 addPtclComponentKEeV.py – Compute Particle Kinetic Energy in eV

This analysis script, addPtclComponentKEeV.py, adds a column to the dataset which provides the particle energies(based on the magnitude of particle velocities) in eV. This column allows energetic particles to be differentiated withinthe simulation. One may also bin and average these quantities using the binning view in the visualize pane. Thisprovides access to the plasma electron temperature, which in turn is important for assessing the mesh size against theDebye length.

Ultrarelativistic calculations of Particle Kinetic Energy in eV

If one of the KEeVx, KEeVy, or KEeVz component options is invoked, the analyzers performs a simplified calculation ofthe kinetic energy, in eV, assuming ultrarelativistic motion in the corresponding direction. Because of the assumptionsavailable, these may be faster than the default KEeV option.

Note: The alternative analyzers, addPtclComponentKEeVx.py, addPtclComponentKEeVy.py, and ad-dPtclComponentKEeVz.py are now deprecated.

254 Chapter 9. Analysis Window

Page 259: VSim In Depth

VSim In Depth, Release 8.2.1

Input Parameters

simulationName (required): The name of this simulation.

speciesName (required): The name of the species for which you wish to append the longitudinal, orcomponent, energy in eV.

addRemoveKEeV (required): Set to either add or remove.

• If add, the component specified in the component argument will be appended to the speciesdataset. If the specified component already exists in an H5 file, the add operation will beignored (on that file only, every file is check individually).

• If remove, the last component of the species dataset will be removed, provided the last compo-nent is one of KEeV, KEeVx, KEeVy, or KEeVz. If no eV component exists in an H5 file, theremove operation will be ignored (on that file only, every file is checked individually).

component (required): Set to one of KEeV, KEeVx, KEeVy, or KEeVz. Note that KEeV is the defaultand more general case. The x, y, z components assume ultrarelativistic motion in the correspondingdirection.

Output

This analysis script, by default, overwrites your existing species data with a file containing the additional column ofenergy in eV.

Alternately, if the addRemoveKEeV is set to remove, it will remove the last component of the dataset if that componentis one of KEeV, KEeVx, KEeVy, or KEeVz.

9.4.3 annotateFieldOnLine.py – Label fieldOnLine diagnostics (beta)

This analysis script, annotateFieldOnLine.py, enables the raw h5 data recorded in a fieldonLine history to be availableas a 2D field containing spatial cell index on the ordinate and time on the abcissa. For fieldonLine histories containingmultiple components, there is an option to choose the index to test.

Input Parameters

simulationName (string, required): The name of this simulation, without suffix.

historyName (string, required): The name of the species to be analyzed.

component (integer, optional): If set, this chooses a specific index of the history.

Output

This analysis script outputs a vizschema file containing 2D data on a uniform cartesian mesh, spatial cell index (alongthe line specified in the history) on the ordinate, time on the abscissa.

9.4.4 annotateSpeciesAbsPtclData2.py – Annotate and combine particles inspeciesAbsPtclData2 history (beta)

This analysis script, annotateSpeciesAbsPtclData2.py, enables the raw h5 data recorded in a speciesAbsPtclData2 his-tory to be available as a field showing the number density of the macroparticles deposited in each cell, and of any otherparameters you have written out. It requires that the first components measured in the history are the particles’ spatial

9.4. VSim Pre-Defined Analysis Scripts 255

Page 260: VSim In Depth

VSim In Depth, Release 8.2.1

coordinates, like ptclAttributes = [xPosition yPosition kineticEnergy current ] for a 2Dsimulation, whether a ZR or xy coordinate system, and is specific to particles collected with collectMethod =recordForEachPtcl.

Input Parameters

simulationName (string, required): The name of this simulation, without suffix.

historyName (string, required): The name of the species to be analyzed.

Output

This analysis script outputs a vizschema field file evaluating the sum of particles deposited in each cell in that timestep,as well as a cumulative sum total.

9.4.5 calculateEmittance.py – Calculate Emittance

This analysis script, calculateEmittance.py, computes the emittance of a beam in Cartesian coordinates and providesvarious other information about a beam. It contains options for analyzing only a section of the longitudinal space, incase the same species has been used for two bunch operation. One should take care with 2D simulations as a greateroverall charge is modelled to obtain an equivalent wake to a 3D simulation with a Gaussian distribution in z. Forthe 2D simulation, there is no Gaussian in z, so charge is uniform and normalized to 1m. It determines whether thespecies is weighted by checking the label of the data in the last column, if it is the particle weight is taken into accuntin the calculation of all the quantities. Please note, that if you have previously used addPtclComponentKEeVx.py,then the weighted column may not be found. The emittances are calculated as the square root of the determinant ofthe covariance matrix whose elements are the products of the averaged position and primed coordinates.

Input Parameters

baseName (required): The name of this simulation.

speciesName (required): The name of the species to be analyzed.

x1plane (optional): If set, this filters the data such that particles with x less than (x1plane-ct) areexcluded from the calculation.

x2plane (optional): If set, this filters the data such that particles with x greater than (x2plane-ct) areexcluded from the calculation.

velLimit (optional): If set, this ensures particles with magnitude of vx, vy or vz greater than the valueprovided here are excluded from the calculation.

Output

This analysis script outputs a csv file containing the RMS values of various phase space coordinates as a function oftime, and also of the longitudinal (x) and transverse (y) emittance.

Usage and testing

Start with the electronBeamDrivenPlasmaT.pre example file, and click on view input file. Underneath

256 Chapter 9. Analysis Window

Page 261: VSim In Depth

VSim In Depth, Release 8.2.1

$ BEAM_GAMMA_INV_2 = BEAM_GAMMA_INV * BEAM_GAMMA_INV

(shortly after 200 lines into the input file) insert the text

$ SIGMA_Y_PRIME = 1.e-3$ SIGMA_Y = BEAM_UX*SIGMA_Y_PRIME

Then in the definition of the velocityGenerator in the species ElectronBeam around line 620 change theexpression for component1.

<STFunc component1>kind = expressionexpression = gauss(SIGMA_Y)

</STFunc>

You then have set both 𝜎𝑦 and 𝜎𝑦′ , so it is possible to simply calculate the geometric and normalized emittance.

Run this file for 5 steps, dumping every step, then click on the analyze tab.

Select the computeEmittance.py analyzer

Set up your options as shown using the base name without extension of your input file, something likeElectronBeamDrivenPlasma1 and the name of the species for analysis ElectronBeam.

Fig. 9.6: Setting up the analyzer

Click on run. The output should look something similar to that shown below

We can see that our SIGMA_R setting further up the filehas translated into 𝜎𝑦 = 2 · 10−5, which is shown, 𝜎𝑦′ =1 · 10−3, so geometric emittance for this uncorrelated case is 𝜖𝑦 = 2 · 10−8. As 𝛾 = 490.2, the normalized emittanceis around under 𝜖𝑦𝑛 = 1 · 10−5.

We can proceed to the visualization tab, select the 1-D fields. You may want to reload data before looking at the results.This is demonstrated in the figure. You can see the emittance in y is constant or decreases by a negligible fraction,transferred to the x component in the self-magnetic field, but due to the beam being completely monoenergetic in x to

9.4. VSim Pre-Defined Analysis Scripts 257

Page 262: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 9.7: Analysis output

start, the x emittance grows rapidly. It is straight forward to add a gaussian function for the BEAM_UX to watch whathappens there too.

9.4.6 calculateFieldMaxAmplitude.py – Check field maximum as a function of time(beta)

calculateFieldMaxAmplitude.py is a python module for reading field data and writing the max amplitude to a history.It can be helpful in charting growth of a plasma wave, or checking that fields remain below the breakdown thresholdwhen a history was not set in the input (.pre or .sdf) file.

Input Parameters

simulationName (string, required): The name of this simulation, without suffix.

fieldName (string, required): The name of the field to be analyzed (e.g. edgeE)

outputFileName (string, optional): If set, this chooses the filename into which to write the history.The default is to suffix the simulation basename with ‘_MaxAbsFieldData’, the component numberand file extension (vsh5)

component (integer, optional): NOT CURRENTLY USED This option in future could allow the userto choose to look at an individual field component. Currently different files are written for eachcomponent. One might consider looking at the total magnitude

√𝐸𝑥2 + 𝐸𝑦2 + 𝐸2

𝑧

258 Chapter 9. Analysis Window

Page 263: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 9.8: 1-D fields showing analysis output over time

Output

This analysis script outputs a vizschema file containing history data with a temporal mesh of dump times rather thanusing the granularity available through using a history. Consequently, use of a history is usually preferable.

9.4.7 computeBeam2ModeCoupling.py – Compute the Beam to Mode Coupling

This analysis script, computeBeam2ModeCoupling.py, computes the RF current in a beam. It convolves the beamcurrent with the dominant mode frequency.

Input Parameters

simulationName (required): The name of this simulation.

JName (required): The name of the current density field to analyze.

component (required): The component 0,1,or 2 of the current density field to analyze.

frequency (required): The frequency to be analyzed.

starttime (required): The start time of the analyzing.

Output

This analysis script outputs a text file with one column of data of the fundamental RF current as a function of axialposition.

9.4. VSim Pre-Defined Analysis Scripts 259

Page 264: VSim In Depth

VSim In Depth, Release 8.2.1

9.4.8 computeCumulativeSumHistory.py – Sum a history (beta)

This analysis script, computeCumulativeSumHistory.py, takes a history and produces a cumulative sum of that history,for example to get a total charge from a history contianing the current incident on a particular surface.

Input Parameters

simulationName (string, required): The name of this simulation, without suffix.

historyName (string, required): The name of the history to be analyzed.

newHistoryName (string, required): The name of the new to be written containing cumulativesum/integral.

multiplier (float, required): Optionally multiply history by a factor, eg the variable of integration,dt multicomponent dataset. Currently unused.

component (integer, optional): If set, this chooses a specific index of the history in a multicomponentdataset. Currently unused.

Output

This analysis script outputs a vizschema file containing 2D data on a uniform cartesian mesh, spatial cell index (alongthe line specified in the history) on the ordinate, time on the abscissa. It is typically available as a 1D plot.

9.4.9 computeDebyeLength.py – Computing the Debye Length (cylindrical only)(beta)

This analysis script, computeDebyeLength.py, generates particle number density, temperature and Debye length, andcreates a dataset for visualisation containing the fraction of Debye length occupied by each mesh cell, based on thedata in particle files.

Currently this only works for cylindrical ZR simulations, but it is anticipated it will be expanded to cope with othercoordinate systems during the VSim 8.x series.

Input Parameters

simulationName (string, required): The name of this simulation.

speciesName (string, required): Name of the electron species for which particle number density tobe calculated. Please note: if there is more than one electron species, the calculation may not bevalid.

threshold (float, optional) Specifies a number of macroparticles per cell below which a measurementof temperature would be meaningless. Disabled in the current version.

Output

This analysis script outputs particle number density (/𝑚3), temperature (𝑇 = 32 · 𝑘𝐵), and the ratio of debye length

measured in the units of the maximum grid dimension at that point (𝐷 = 𝜆𝐷/∆𝑥), all data as vizschema compliantfields visualisable in Composer. A high value, greater than 10, is an indication that the Debye length is well resolved.A value less than 1 means that the Debye length is not resolved, and is an indication that particles in the simulation arelikely to artificially heat. Some mitigation is possible with higher order particles but normally the best solution is to

260 Chapter 9. Analysis Window

Page 265: VSim In Depth

VSim In Depth, Release 8.2.1

increase the grid resolution. These density fields can help to analyze the particle distribution results in the simulationdomain.

9.4.10 computeFarFieldFromKirchhoffBox.py – Far Field Analysis

This analysis script, computeFarFieldFromKirchhoffBox.py, analyzes a “Far-Field Box Data” history generated byVorpal. (The Kirchohoff Box should surround all structures but be a few cells inside any boundary cells, including thecells associated with any MALs or PMLs.

The start time should be set to a time that allows for the desired signal to have reached all points on the Kirchhoff Box.This is typically rise time of the pulse plus the time to cross the far-field box diagonal.

The end time of the box is typically the start time plus another box crossing time or two, plus the desired length oftime one wished to have in the far field, for example one or two cycles of an oscillating signal. The simulation can endafter the end time of the box.

This script calculates the far fields at the specified points on the far sphere, as desginated by the sphere radius and anumber of points in theta and phi spherical angles.

It then puts that data along with the field magnitude on an spherical mesh that can be visualized with VSimComposerin a separate file for each analysis time. It does this for multiple far field times, as controlled by the timeStepStrideparameter.

The full list of user settable parameters is below.

Input Parameters

simulationName (required): The name of the input file without the extension. The default should bepresent.

fieldName (required): The name of the field for which the far field is desired. This defaults to E,which should work.

farFieldRadius (required): The radius at which the far field will be calculated. This is typically setto a number that is large (10x is reasonable) compared with the size of the Kirchoff Box. However,the algorithm remains accurate for any radius outside the Kirchoff Box, even if that is technically inthe radiation near field.

timeStepStride (required): From the first calculation of the far field, how often should it calculatethe far field, as a multiplier of the simulation time step.

numTheta (required): The number of theta points to be calculated.

numPhi (required): The number of phi points to be calculated.

zeroThetaDirection (required): A vector pointing to where the polar angle is zero, typically thepositive z direction.

zeroPhiDirection (required): A vector pointing to where the azimuthal angle is zero, typically thepositive x direction.

Output

This analysis script outputs a series of HDF5 files named <simulationName>_FarField<fieldName>_NN.vsh5, where<simulationName> is the name of the simulation, and <fieldName> (e.g, E)is the field for which the far field is beingcalculated. This data can be seen in the Visualize tab under Data Overview Scalar Data as farE (if E is the fieldName).If the Visualize tab has already been opened the Reload Data button must be clicked in order to load the new data.

9.4. VSim Pre-Defined Analysis Scripts 261

Page 266: VSim In Depth

VSim In Depth, Release 8.2.1

The dumps are not synchronized with the regular vorpal data dumps, because the far field times may be strongly timedelayed due to the large far field radius. Instead these dumps start at number 0, with the first far field analysis time,which is computed internally to be consistent with the required data being available in the Kirchhoff Box data stream.E.g., this time is delayed from the first dump time by half, or more, of a box diagonal transit time, depending on thecentering of the Kirchhoff Box. Far field dumps are then output every timeStepStride as long as the necessarydata for the computation is available in the Kirchhoff Box data stream.

Further analysis of these dumps is possible to get a single frequency amplitude, and is often done with a user-generatedcustom script. Such scripts can also be provided upon request.

Example

For an example usage of this analysis script, see the predatordrone-analysis section of the predatordrone VSimEMexample.

9.4.11 computeFarFieldRadiation.py – Far Field Analysis

This analysis script, computeFarFieldRadiation.py, analyzes a user-specified history. It will assemble a far field historyinto a plottable far field pattern. This allows for examination of the far field parameters, or radar cross section of aparticular object. The size of the sphere used as the near field is specified in the .pre file, typically with the variablename RS.

Input Parameters

simulationName (required): The name of the input file. Note that the file extension should NOT beincluded in this text field.

historyName (required): The name of the history dataset. Typically farField or RCS. Note that thefile extension should NOT be included in this text field.

numPhi (required): The number of phi points in the history. Specified in the input file.

numTheta (required): The number of theta points in the history. Specified in the input file.

numTime (required): The number of time points spanning the far field time interval. May havebeen specified in the input file as NTFAR. Otherwise it is 16.

SLL (required): The lowest side lobe level (dB) If set to -40 side lobes down to -40 dB will be displayed.

normalize (required): If set to 1 the dB gain values will be scaled so that the highest is 1. If set to 0there is no change.

Output

This analysis script outputs a .h5 file, titled dataset_farField.vsh5. In the Visualize tab of VSimComposer it is visual-izable in Scalar Data. Note that if the Visualize tab has already been opened the Reload Data button must be clickedin order to load the new file.

Example

For an example usage of this analysis script, see the advanceddipoleaboveconductingplane-analysis section of theadvanceddipoleaboveconductingplane VSimEM example.

262 Chapter 9. Analysis Window

Page 267: VSim In Depth

VSim In Depth, Release 8.2.1

9.4.12 computeFieldCrossProduct.py – Compute cross product between two fields(beta)

This analysis script computeFieldCrossProduct.py is used to perform a cross product of two different vector fields.

A typical application would be as a step toward determination of laser intensity by taking the cross product of nodal Eand B fields (so that they are co-located). There is an optional multiplier, so that the 1/mu factor can be included.

The poynting vector represents only instantaneous power, and so time averaging would need to be employed to workout intensity.

Input Parameters

simulationName (string, required): The name of this simulation, without suffix.

field1Name (string, required): The name of the first cartesian vector field to be analyzed.

field2Name (string, required): The name of the second cartesian vector field to be analyzed.

outputFieldName (string, required): The name of the field to be written.

multiplier (float, required, default 1.0): Multiple by which to scale the output field. e.g. to createlaser intensity use 1/𝜇0 = 1/1.25663 × 10−6 = 795774.7

Output

This analysis script outputs a set of vizschema compatible field files containing the cross product of the two vectorfields provided.

9.4.13 computeInverseQ.py – Compute Inverse Q Analysis

This analysis script, computeInverseQ.py, computes the inverse Q from a time series. For an oscillating historywith amplitude damping rate 𝜔/2𝑄, calculates the quantity 1/𝑄, where 𝜔 = 2𝜋× frequency.

Input Parameters

simulationName (required): The name of this simulation.

historyName (required): The history to analyze.

frequency (required): The frequency at which history will be analyzed.

Output

This analysis script outputs two columns of data with the titles “Time (s)” and “Inverse Q”.

Example

For an example usage of this analysis script, see the klystron-analysis section of the klystron VSimMD example.

9.4. VSim Pre-Defined Analysis Scripts 263

Page 268: VSim In Depth

VSim In Depth, Release 8.2.1

9.4.14 computeLineIntegral.py – Compute the line integral of an electric field (beta)

This analysis executable, computeLineIntegral.py, takes an electric (or more generally, any edge centered) field andcomputes the line integral along a user specified curve.

To make this script available in a simulation, analyzers = [computeLineIntegral] must be added in theXSim block.

Input Parameters

simulationName (required): The name of the simulation.

geometryName (required): The name of the geometry grid boundary.

fieldName (required): The name of the field to be integrated.

beginDump (optional): The first memory dump to process, defaults to 0.

endDump (optional): The last memory dump to process, defaults to all.

nUCells (optional): The number of curve segments, defaults to 1.

xCurveExpression (required): Expression specifying x(u) along the curve, with 0 <= u <= 1. Sup-ported mathematical functions are sin, cos, sqrt, atan, atan2, cosh, sinh, exp, tanh, log, log10. Sup-ported constants are pi and e. The curve must be fully inside the domain.

yCurveExpression (required): Expression specifying y(u) along the curve, with 0 <= u <= 1. Sup-ported mathematical functions are sin, cos, sqrt, atan, atan2, cosh, sinh, exp, tanh, log, log10. Sup-ported constants are pi and e. The curve must be fully inside the domain.

zCurveExpression (required): Expression specifying z(u) along the curve, with 0 <= u <= 1. Sup-ported mathematical functions are sin, cos, sqrt, atan, atan2, cosh, sinh, exp, tanh, log, log10. Sup-ported constants are pi and e. The curve must be fully inside the domain.

outputFieldName (optional): The output field name, will be constructed from geometryName andfieldName if not provided.

Output

This analysis script outputs .vsh5 files, titled simulationName*_*outputFieldName*_dumpNumber.vsh5. This fieldcan be found in the *Visualize tab of VSimComposer and can be visualized in Scalar Data. Note that if the Visualizetab has already been opened the Reload Data button must be clicked in order to load the new files.

Example

For an example usage of this analysis script, see the rcs-analysisT section of the rcsT VSimEM example.

9.4.15 computePtclLimits.py – Locate particles with highest or lowest values alongcoordinates (beta)

This analysis script, computePtclLimits.py, helps locate particles which have breached the computational domain.This helps determine where they may have come from to identify potential issues with sources and sinks. Additionallythe analyzer writes a ‘history’ type particle dataset with a time mesh given by dumps which can be plotted on one axisagainst the extents of the species coordiantes as they vary through the simulation. As such it can also find the fastestparticles in a simulation, which is useful for checking timesteps and mesh size is OK.

264 Chapter 9. Analysis Window

Page 269: VSim In Depth

VSim In Depth, Release 8.2.1

Input Parameters

simulationName (string, required): Base simulation name, i.e., the input file name without exten-sion.

speciesName (string, required): Name of the species to analyze.

outputFileName (string, optional) Filename to write the history output containing maximum andminimum particle coords for each timestep. The default is simulationname_MaxMinData_*.vsh5.If a filename is given, the user should include the baseName and the extension .vsh5

Output

The output is a vizschema compatible dataset containing a set of ‘history’ or 1D vs time data. The contents will bexmax, ymax, vxmax, vymin, etc. and should be equally suited to cylindrical and cartesian datasets.

9.4.16 computePtclNumDensity.py – Particle Number Density Analysis

This analysis script, computePtclNumDensity.py, generates number density fields based on a set of particle data files.It works in 1D, 2D, and 3D Cartesian, as well as 2D RZ cylindrical.

The script can optionally perform a spatial average on the resulting data set. The spatial average is weighted andcomputed over an NxN square kernel. The size of the kernel and number of iterations are specified in the analyzerinput. For example, if we set avgNxN to 5, the kernel would be weighted like this:

1 2 4 2 12 4 8 4 24 8 16 8 42 4 8 4 21 2 4 2 1

Setting iterateAvg to 2, will perform the averaging twice, for a smoother result.

Note that spatial averaging can become very slow for kernels much larger than 3, especially if the number of iterationsis 2 or more, or if the dimensionality is 3.

Input Parameters

simulationName (required): The name of this simulation.

speciesName (required): Name of the species for which particle number density to be calculated.

avgNxN (required): Determines the size of the averaging kernel. Type an odd integer for N, and kernelwill be N long in 1D, NxN in 2D, or NxNxN in 3D. Set to 1 if no averaging is desired.

iterateAvg (required): If avgNxN > 1, this is the number of iterations of the spatial averaging func-tion. Ignored if avgNxN = 1.

Output

This analysis script outputs particle number density data as fields. These density fields can help to analyze the particledistribution results in the simulation domain. The files written will have the .VSH5 file extension and will show upunder Scalar Data on the Visualization pane as speciesNameDensity.

9.4. VSim Pre-Defined Analysis Scripts 265

Page 270: VSim In Depth

VSim In Depth, Release 8.2.1

Example

For an example usage of this analysis script, see the ionThrusterT-analysis section of the ionThrusterT VSimPDexample.

9.4.17 computeS11Parameters.py – S11 Parameter Script

This analysis script, computeS11Parameters.py, calculates the S11Parameter at one point between two sets of electro-magnetic field data. For the history to work correctly the simulation must have at least two seperate sets of electro-magnetic fields.

Input Parameters

simulationName (required): The name of this simulation.

historyCAL (required): The name of the history used in the calibration run.

historyPATCH (required): The name of the history used in the test run.

nElements (required): The number of time steps in the simulation run.

nPoints (required): The number of points to analyze within the history.

dt (required): The length of one time step (can be found in the run tab under Runtime Options.

nZeros (required): The total length of the FFT. Can be used for zero padding.

Output

This analysis script outputs a vizSchema file of the title dataset_SParameters.h5 . It is visualizable as a 1D-field Notethat if the Visualize tab has already been opened the Reload Data button must be clicked in order to load the new file.

Example

For an example usage of this analysis script, see the patchantennat-analysis section of the patchantennat VSimEMexample.

9.4.18 computeSpectrogram.py – Make spectrogram (beta)

This analysis script, computeSpectrogram.py, takes a history of field at a coordinate or cell index, and works out thespectrogram, writing it into a 2D dataset containing frequency vs time whichh may be viewed in VSimComposer.

Input Parameters

simulationName (string, required): The base name of this simulation without extension.

historyName (string, required): Name of history dataset to analyze. eg E1

fourierTransSize (integer, required): Number of timesteps (or history points) to use for eachfourier transform. Determines lowest measurable frequency in the transform.

noOverlap (integer, required): Number of timesteps that will overlap between successive measure-ments of frequency. Set this to between zero and the size of the fourier transform.

266 Chapter 9. Analysis Window

Page 271: VSim In Depth

VSim In Depth, Release 8.2.1

maxFreq (float, required): When preparing the data, discard frequencies above this maximum fre-quency. FFTs show a maximum frequency corresponding to 2*dt. This is higher than any frequencyyou are reliably going to be able to calculate.

window (integer, required): Specify a windowing function for the spectrogram Default is 1 - Hanning.1) Hanning 2) Hamming 3) Blackmann 4) Bartlett If you are unfamiliar with these functions, pleaseconsult numpy documentation.

component (integer, optional): Component to select if history contains multicomponent data. Default= 0

fracTime (string, optional): This feature was available in some alpha versions of the script, and wouldallow the user to wait until later in the simulation before starting the data plotting. It has now beendeprecated, disabled and will be removed completely in future versions.

Output

This analysis script outputs a vizschema compatible hdf5 file containing a 2D field readable in VSimComposer, timeon the ordinate, frequency on the abcissa.

9.4.19 computeSurfaceFlux.py – Compute the flux integral of a magnetic field(beta)

This analysis executable, computeSurfaceFlux.py, takes a magnetic (or more generally, any face centered) field andcomputes the flux integral on a user specified surface.

To make this script available in a simulation, analyzers = [computeSurfaceFlux] must be added in theXSim block.

Input Parameters

simulationName (required): The name of the simulation.

geometryName (required): The name of the geometry grid boundary.

fieldName (required): The name of the field to be integrated.

beginDump (optional): The first memory dump to process, defaults to 0.

endDump (optional): The last memory dump to process, defaults to 0.

nUCells (optional): The number of cells in the u parametric direction, defaults to 1.

nVCells (optional): The number of cells in the v parametric direction, defaults to 1.

xSurfaceExpression (required): Expression specifying x(u, v) for a surface, with 0 <= u, v <= 1.Supported mathematical functions are sin, cos, sqrt, atan, atan2, cosh, sinh, exp, tanh, log, log10.Supported constants are pi and e. The surface must be fully inside the domain.

ySurfaceExpression (required): Expression specifying y(u, v) for a surface, with 0 <= u, v <= 1.Supported mathematical functions are sin, cos, sqrt, atan, atan2, cosh, sinh, exp, tanh, log, log10.Supported constants are pi and e. The surface must be fully inside the domain.

zSurfaceExpression (required): Expression specifying z(u, v) for a surface, with 0 <= u, v <= 1.Supported mathematical functions are sin, cos, sqrt, atan, atan2, cosh, sinh, exp, tanh, log, log10.Supported constants are pi and e. The surface must be fully inside the domain.

outputFieldName (optional): The output field name, will be constructed from geometryName andfieldName, if not provided.

9.4. VSim Pre-Defined Analysis Scripts 267

Page 272: VSim In Depth

VSim In Depth, Release 8.2.1

Output

This analysis script outputs .vsh5 files, titled simulationName*_*outputFieldName*_dumpNumber.vsh5. This fieldcan be found in the *Visualize tab of VSimComposer and can be visualized in Scalar Data. Note that if the Visualizetab has already been opened the Reload Data button must be clicked in order to load the new files.

Example

For an example usage of this analysis script, see the rcs-analysisT section of the rcsT VSimEM example.

9.4.20 computeTimeSeriesAmplitude.py – Time Series Amplitude Analysis

This analysis script, computeTimeSeriesAmplitude.py, computes the amplitude of a time series. The script calculatesthe instantaneous amplitude of history at the specified frequency.

Input Parameters

simulationName (required): The name of this simulation.

historyName (required): The history dataset to analyze.

frequency (required): The frequency at which history will be analyzed.

Output

This analysis script outputs two columns of data with the titles “Time (s)” and “Amplitude”.

Example

For an example usage of this analysis script, see the klystron-analysis section of the klystron VSimMD example.

9.4.21 computeTimeSeriesFrequency.py – Time Series Frequency Analysis

This analysis script, computeTimeSeriesFrequency.py, computes the frequency vs. time of a time series. The scriptcalculates the instantaneous frequency of history at the specified frequency.

Input Parameters

simulationName (required): The name of this simulation.

historyName (required): The history dataset to analyze.

frequency (required): The frequency at which history will be analyzed.

Output

This analysis script outputs two columns of data with the titles “Time (s)” and “Frequency”.

268 Chapter 9. Analysis Window

Page 273: VSim In Depth

VSim In Depth, Release 8.2.1

Example

For an example usage of this analysis script, see the klystron-analysis section of the klystron VSimMD example.

9.4.22 convertFieldComponentCartToCylX.py – Cartesian Field Components toCylindrical Components Script (x-axis)

The convertFieldComponentCartToCylX.py script (previously cartComptsToCylX.py) analysis script analyzes 3Dvector field data specified on a 3D Cartesian mesh 𝐹𝑥(𝑥, 𝑦, 𝑧), 𝐹𝑦(𝑥, 𝑦, 𝑧), 𝐹𝑧(𝑥, 𝑦, 𝑧) and provides a copy of thefield’s components from a Cartesian system to a cyllindrical polar system around the x-axis of the Cartesian mesh𝐹𝑧′(𝑥, 𝑦, 𝑧), 𝐹𝑟′(𝑥, 𝑦, 𝑧), 𝐹𝜑′(𝑥, 𝑦, 𝑧). We treat the system as right handed, so the angle 𝜑′ increases from the (Carte-sian) y-axis towards the z-axis, and 𝑧′ = 𝑥 points perpendicular from the plane swept out by 𝜑′.

Input Parameters

fieldName (required): The name of the field to be analyzed with a Cartesian coordinate system. i.e.edgeE or faceB

baseName (required): The name of the runspace to be opened, this usually corresponds to the simula-tion name. i.e magnetron2D

Output

This analysis script outputs an hdf5 file, titled baseName_fieldNamexRPhi.h5, i.e. magnetron2D_edgeExRPhi. Thefields will be available in the Visualize tab of VSimComposer under Scalar Data, where there will be a list of threecomponents, 0,1 and 2 which map to 𝑧′, 𝑟′ and 𝜑′ respectively.

Note that if the Visualize tab has already been opened the Reload Data button must be clicked in order to load the newfile.

9.4.23 convertFieldComponentCartToCylZ.py – Cartesian Field Components toCylindrical Components Script (z-axis)

The convertFieldComponentCartToCylZ (previously cartComptsToCylZ.py) analysis script analyzes 3D vector fielddata specified on a 2D or 3D Cartesian mesh 𝐹𝑥(𝑥, 𝑦, 𝑧), 𝐹𝑦(𝑥, 𝑦, 𝑧), 𝐹𝑧(𝑥, 𝑦, 𝑧) and provides a copy of thefield’s components from a Cartesian system to a cyllindrical system around the z-axis of the Cartesian mesh𝐹𝑧′(𝑥, 𝑦, 𝑧), 𝐹𝑟′(𝑥, 𝑦, 𝑧), 𝐹𝜑′(𝑥, 𝑦, 𝑧). We treat the system as right handed, so the angle 𝜑′ increases from the (Carte-sian) x-axis towards the y-axis, and 𝑧′ = 𝑧 points perpendicular from the plane swept out by 𝜑′.

Additionally, this script also adds a derived 2D vector to the input hdf5 file that contains the X and Y components ofthe field, which enables quiver plots for the field data for simulations on 2D meshes. Typically this might be used forplotting magnetic field data in cartesian plots.

Input Parameters

fieldName (required): The name of the field to be analyzed with a Cartesian coordinate system. i.e.edgeE or faceB

baseName (required): The name of the runspace to be opened, this usually corresponds to the simula-tion name. i.e magnetron2D

9.4. VSim Pre-Defined Analysis Scripts 269

Page 274: VSim In Depth

VSim In Depth, Release 8.2.1

Output

This analysis script outputs an hdf5 file, titled baseName_fieldNamezRPhi.h5, i.e. magnetron2D_edgeEzRPhi. Thefields will be available in the Visualize tab of VSimComposer under Scalar Data, where there will be a list of threecomponents, 0,1 and 2 which map to 𝑧′, 𝑟′ and 𝜑′ respectively.

Note that if the Visualize tab has already been opened the Reload Data button must be clicked in order to load the newfile.

9.4.24 convertPtclComponentsCartToCylX.py – Generate cylindrical particle coor-dinates in cylindrical coords from carteisan simulation (beta)

Sometimes we perform simulations with natural cylindrical symmetry in cartesian coordinates to avoid issues arisingfrom the small timestemp that small cells near the axis causes. It is helpful to interpret the results in cylindricalcoordinates, rather than the cartesian coordinates of the simulation mesh. This analyzer performs the conversion ofthe particle coordinates and the particle velocity. New _r, _phi, _vr, _vphi columns are added to the particle file’scoordinates. If one is wishing to restart, these columns will need removing before proceeding. This assumes the x-axisin the cartesian simulation would correspond to z’, the coordinate along r=0 in the cylindrical coordinate system. zand vz in the transformed frame is not written, as this is simply the same as x and vx in the original system, which arealready present in the dataset.

Input Parameters

simulationName (string, required): Base simulation name, i.e., the input file name without exten-sion.

speciesName (string, required): Name of the species onto which you want to write cylindrical coor-dinates.

Output

This analysis script updates the species datafile, adding _r and _phi components for both position and velocity. Asx->z’, there is no new component required for z.

Example usage

This analysis script may be useful for interpreting the klystron and helix TWT examples in VSim for MicrowaveDevices, which naturally have particles travelling down a cylindrical beampipe oriented along x.

9.4.25 convertPtclComponentsCartToCylZ.py – Generate cylindrical particle coor-dinates in cylindrical coords from carteisan simulation (beta)

convertPtclComponentsCartToCylZ.py differs from convertPtclComponentsCartToCylX.py as it assumes the z axis ofthe original cartesian simulation and of the axis of the cylindrical coordinate system is shared.

Sometimes we perform simulations with natural cylindrical symmetry in cartesian coordinates to avoid issues arisingfrom the small timestemp that small cells near the axis causes. It is helpful to interpret the results in cylindricalcoordinates, rather than the cartesian coordinates of the simulation mesh. This analyzer performs the conversion ofthe particle coordinates and the particle velocity. New _r, _phi, _vr, _vphi columns are added to the particle file’scoordinates. If one is wishing to restart, these columns will need removing before proceeding. This assumes the z-axisin the cartesian simulation would correspond to z’, the coordinate along r=0 in the cylindrical coordinate system. z

270 Chapter 9. Analysis Window

Page 275: VSim In Depth

VSim In Depth, Release 8.2.1

and vz in the transformed frame is not written, as this is simply the same as z and vz in the original system, which arealready present in the dataset.

Input Parameters

simulationName (string, required): Base simulation name, i.e., the input file name without exten-sion.

speciesName (string, required): Name of the species onto which you want to write cylindrical coor-dinates.

Output

This analysis script updates the species datafile, adding _r and _phi components for both position and velocity. Asz->z’, there is no new component required for z.

Example usage

This analysis script may be useful for interpreting the 2D magnetron example in VSim for Microwave Devices, whichhas particles travelling in x,y space with a cylindrical central cathode oriented along z.

9.4.26 createMissingPtclsDumps.py – Add small particle datasets to synchronizevisualization (beta)

createMissingPtclsDumps.py writes near empty particle dump files for any missing particle dumps. This writes nearempty particle dump files for any missing particle dumps. This corrects a defficiency in VisIt, which does not knowhow to handle missing dumps and instead continues to display the previous particle dump of the simulation. It auto-matically determines all species in the .pre file and checks for field dumps without a corresponding particle dataset foreach species.

Input Parameters

simulationName (string, required): Base simulation name, i.e., the input file name without exten-sion.

Output

For each species, createMissingPtclsDumps.py writes simulationname_speciesname_NN.h5, for each value of NN nothaving a particle dump but having field dumps.

9.4.27 createParticleTracks.py – Make files which track particle trajectories (beta)

This analysis script, createParticleTracks.py, will write a new file for each particle that you wish to track over time.This requires the use of tagged particle species with a unique tag identifier for each particle.

The new .h5 file will contain the particle positions and velocities for each time dump of your simulation. Since theanalyzer reads in the data from existing species dump files (e.g. simulation_electrons_*.h5), it is beneficial to set yoursimulation to dump frequently.

9.4. VSim Pre-Defined Analysis Scripts 271

Page 276: VSim In Depth

VSim In Depth, Release 8.2.1

Note: This analyzer requires tagged particle species, as the order of particles may be affected by particle creation,removal and sorting operations.

Input Parameters

simulationName (string, required): Base simulation name, i.e., the input file name without exten-sion.

speciesName (string, required): Name of the tagged species that contains the particle to be tracked.

ptclIndex (int, required) Tag ID of the particle to be tracked.

Output

createParticletclsTracks.py writes simulationname_speciesnameTrackNN_0.h5, for each value of NN whereNN=ptclIndex is the tag number in the particle file to use.

9.4.28 extractModes.py –Extract Modes Analysis Script

This analysis script, extractModes.py, intended to be used for simulation runs without particles, determines the naturalmode frequencies and mode patterns of a cavity using the Filter Diagonalization Method (FDM) [1].

Input Parameters

simulationName (required): The name of this simulation.

field (required): Name of the electric or magnetic field to which the FDM method is applied.

beginDump (required): Initial dump number at which the FDM method is performed, which mustoccur at a time after the source excitation has been turned off.

endDump (required): Ending dump number at which the FDM method is performed.

nDim (required): Number of dimensions in the simulation.

nModes (required): Number of potential modes in the frequency range.

sampleType (required): Sampling type (0 for uniform, 1 for random).

numberUniformPts (required if sampleType=0): Number of uniform points to sample in each di-rection (only applied if sampleType=0).

numberRandomPts (required if sampleType=1): Number of random points to sample (only appliedif sampleType=1).

Output

This analysis script outputs three columns of data with the titles “freq [Hz]” (eigenmode frequency), “invQ” (inversequality factor), and “SVD” (singular value decomposition), and creates new eigenmode fields that may be viewed inthe VSimComposer Visualize tab. For example, a simulation with a magnetic field faceB would have the scalar fieldsfaceB_0/1/2 (eigenmode) in addition to the magnetic fields faceB_0/1/2 (faceB).

272 Chapter 9. Analysis Window

Page 277: VSim In Depth

VSim In Depth, Release 8.2.1

Example

For an example usage of this analysis script, see the crabCavityT-analysis section of the crabCavityT VSimEM exam-ple.

Usage Recommendations

Current Source

It is recommended that the current source used to excite a cavity take the following form

𝐼 (𝑡) = 𝐼0

{sin [2𝜋𝑓ℎ𝑖 (𝑡− 𝜏/2)] − sin [2𝜋𝑓𝑙𝑜 (𝑡− 𝜏/2)]

2𝜋 (𝑓ℎ𝑖 − 𝑓𝑙𝑜) (𝑡− 𝜏/2)

}exp

[− (𝛿𝑓)

2(𝑡− 𝜏/2)

2]𝐻 (𝜏 − 𝑡)

as depicted in Fig. 9.9

Fig. 9.9: Time and frequency space plots of current source

𝐼0 = 𝐼 (𝜏/2) is the maxmimum current, 𝜏 = 2𝑢2/𝜋𝛿𝑓 is the duration of the excitation, 𝑓𝑙𝑜 and 𝑓ℎ𝑖 are respectivelythe lower and upper frequency limits of the excitation, 𝐻 is the Heaviside function, and 𝛿𝑓 and 𝑢 together control thesteepness of the frequency spectrum near 𝑓𝑙𝑜 and 𝑓ℎ𝑖. The ratio of the frequency space current source amplitude forfrequencies outside the interval [𝑓𝑙𝑜 − 𝛿𝑓, 𝑓ℎ𝑖 + 𝛿𝑓 ] to those inside the interval can be specified by the parameter 𝑢with the following table:

Ratio 𝑢10−4 2.7610−5 3.1310−6 3.4610−7 3.7710−8 4.06

The input parameter initialDump should be set to a dump for which 𝑡 > 𝜏 .

9.4. VSim Pre-Defined Analysis Scripts 273

Page 278: VSim In Depth

VSim In Depth, Release 8.2.1

Frequency Parameter

There are some rough guidelines for choosing a suitable value of the parameter 𝛿𝑓 :

• If examining the low end of a spectrum, where the mode density is not too high, 𝛿𝑓 ≈ 𝑓𝑙𝑜/4 is reasonable.

• If examining a narrow range of frequencies at the high end of a spectrum, 𝛿𝑓 ≈ (𝑓ℎ𝑖 − 𝑓𝑙𝑜) /4 is reasonable.

• If intentionally trying to exclude modes outside of, but close to, the nominal spectrum from 𝑓𝑙𝑜 to 𝑓ℎ𝑖, a smallervalue of 𝛿𝑓 may be necessary. If 𝛿𝑓 is too small, however, heavily damped modes may disappear entirely.

• If anticipating modes with loss parameter 𝑄𝑚 near frequency 𝑓𝑚, 𝛿𝑓 should satisify 𝛿𝑓 ≥ 2𝑓𝑚/𝑄𝑚 to ensurethe modes are present after the excitation turns off.

• For loss-less systems where 𝑄 → ∞, 𝛿𝑓 may be as small as desired.

• issing modes may occur if the duration of the simulation is too large, causing modes with finite decay to disap-pear (in which case, 𝛿𝑓 should be increased).

Dump Interval and Number

The following are some guidelines for choosing the dump interval and number of dumps, endingDump -initialDump.

• The dump interval should be smaller than half a period of the highest frequency present.

• The number of dumps should cover at least one cycle of the smallest frequency present.

• There should be at least three times as many dumps as the number of modes found.

References

[1] G. R. Werner and J.R. Cary, “Extracting modes and frequencies from time-domain simulations with filter-diagonalization”, J. Comp. Phys., 227 (10), 5200-5214, 2008.

9.4.29 performLowPassFilter.py – Perform Low Pass Filter

This analysis script, performLowPassFilter.py, is a low pass filter on a time series. The script performs a boxcar filterof history of width equal to one period of the specified frequency.

Input Parameters

simulationName (required): The name of this simulation.

historyName (required): The history to analyze.

frequency (required): The frequency at which history will be analyzed.

outputFileName (Optional): Name of the output vsh5 file that the transformed time series will bewritten in to. Default is SIMULATIONNAME_lowPassFilter_.vsh5

Output

This analysis script outputs two columns of data with the titles “Time (s)” and “Low Pass Filter”.

274 Chapter 9. Analysis Window

Page 279: VSim In Depth

VSim In Depth, Release 8.2.1

Example

For an example usage of this analysis script, see the klystron-analysis section of the klystron VSimMD example.

9.4.30 performTwoHistoryArithmetic.py – Perform Mathematical Operations on twohistories (beta)

performTwoHistoryArithmetic.py is a python analyzer for mathematically manipulating two histories from the samesimulation and writing the result (sum, multiple, subtraction, division) to a third history. First we will look for historiesin individual vsh5 files named baseName_history.vsh5 and if we do not find them we’ll check the regular history file.This behaviour reduces problems on restart.

Input Parameters

simulationName (string, required): The name of this simulation.

history1Name (string, required): The first history to use in the mathematical operation. H1.

history2Name (string, required): The second history to use in the mathematical operation. H2.

newhistoryName (string, required): The history name in which to record the result. H3.

operation (string, required):

The mathematical operation to be applied: a: H3=H1+H2 m: H3=H1*H2 d: H3=H1/H2 s:H3=H1-H2

Output

The output is a vizschema compatible history file called simulationName_newHistoryName.vsh5 containing the result.This result should be available in VSimComposer.

Example

Consider the case where you have two different particle species incident on a wall, and separate absorbers for both.You may include histories for just the individual species within the simulation input, and combine them using thisanalyzer to determine the net current afterwards.

9.4.31 putFieldOnSurfaceMesh – Put Field On Surface Mesh

This analysis executable, putSurfaceFieldOnMesh.exe, takes a user-specified field and “paints” field components andmagnitude onto a perfectly conducting boundary surface, which intersects the grid. Appropriate boundary conditionsare inferred depending on the type of field (electric or magnetic). Only those elements of the field projected on theconducting surface will be displayed. A common use of this tool is to view the surface currents on an object.

To make this script available in a simulation, analyzers = [putFieldOnSurfaceMesh] must be added inthe XSim block.

9.4. VSim Pre-Defined Analysis Scripts 275

Page 280: VSim In Depth

VSim In Depth, Release 8.2.1

Input Parameters

simulationName (required): The name of the simulation.

geometryName (required): The name of the conducting geometry.

fieldName (required): The name of the field to be painted on the grid boundary.

beginDump (optional): The first memory dump to process, defaults to 0.

endDump (optional): The last memory dump to process, defaults to 0.

outputFieldName (optional): The output field name, will be constructed from geometryName andfieldName, if not provided.

Output

This analysis script outputs .vsh5 files, titled simulationName*_*outputFieldName*_dumpNumber.vsh5. This field canbe found in the *Visualize tab of VSimComposer and can be visualized in Scalar Data. Note that if the Visualize tabhas already been opened the Reload Data button must be clicked in order to load the new files. If the prefile generatesa magnitude field, this will be available for the “painted” field.

Example

For an example usage of this analysis script, see the rcs-analysisT section of the rcsT VSimEM example.

9.4.32 subselectparticles.py – Subselect Particles (beta)

This analysis script, subselectParticles.py, writes new particle datasets containing a subselection of the particles basedon position, velocity, or other component based filtering criterea.

Input Parameters

simulationName (required): The name of this simulation.

speciesName (required): The name of the species which is the source of the subselection operation.

outputSpeciesName (optional): The name of the file to write, and the species dataset name.

component (int, optional): The component index to filter. Depends on species kind and dimensional-ity.

lowerBounds (float, optional): Particles are removed with component values less than lowerBounds.

upperBounds (float, optional): Particles are removed with component values greater than upper-Bounds.

flipLimits (optional): Where upper and lower bounds are both provided, this allows subselectingparticles outside the range, rather than inside.

move (optional): (currently not enabled).

Output

This analysis script outputs a set of vizschema compatible hdf5 files readable in VSimComposer, VisIt and other toolscontaining a filtered set of particles.

276 Chapter 9. Analysis Window

Page 281: VSim In Depth

VSim In Depth, Release 8.2.1

9.5 User’s Guides to help create Analysis Scripts

9.5.1 VsHdf5 User’s Guide

VsHdf5 Introduction

VsHdf5 is a collection of Python classes that provide an interface between VizSchema and Hdf5. These classes makeit easy to read and write VizSchema-compliant files, which may be the result of simulation code dumps or analysisscripts. VizSchema-compliant files may be visualized in Composer, or other visualization software, such as VisIt.

Requirements

VsHdf5 has been developed using Python 2.7. It works with Python 2.6 as well, and probably Python 3.0 althoughthat is currently not tested. VsHdf5 must be able to import pytables and numpy. When importing VsHdf5 if thesemodules can not be loaded, an exception is thrown. VsHdf5 supports VizSchema version 2.1.

Usage

To use VsHdf5, first make sure that VsHdf5 (and numpy and pytables) are in your PYTHONPATH. Then simply use:

import VsHdf5

in your Python script.

Reading in VizSchema data from a file

To read an object from an existing VizSchema-compliant file in your Python script, simply create the object and passin the name of the file and the name of the object in the file:

obj = VsHdf5.Object(fileName=filename, name=objectname)

where Object could be one of:

• Dataset

– Field

– History

– Particles

• Group

– RunInfo

– TimeGroup

– Limits

• Mesh

– StructuredMesh

– UnstructuredMesh

– UniformCartesianMesh

– RectilinearMesh

9.5. User’s Guides to help create Analysis Scripts 277

Page 282: VSim In Depth

VSim In Depth, Release 8.2.1

So for instance, to read particles from a Vorpal dump file from a species called electrons, you could write:

e = VsHdf5.Particles(fileName='baseName_electrons_1.h5', name='electrons')

This will create an object called ‘e’ in Python, that contains both the data in the dataset ‘electrons’ in the file ‘base-Name_electrons_1.h5’, as well as the attributes associated with that data. The data can be accessed as

e.dataset

or

e[:]

both of which are a numpy array, and can be sliced and manipulated with the usual numpy operators. You can get alist of the attributes that were stored in the dataset in the file by invoking

attrs = e.attributeList

which will return a dictionary with key/value pairs representing the attributes.

For objects that do not have datasets (those that are Hdf5 groups with only attributes in the file), then dataset = None.

Optionally, you can specify a location in the Hdf5 file from which to read the data or group:

e = VsHdf5.Particles(fileName='baseName_electrons_1.h5', name='electrons', location =→˓'/fluids')

If not specified, the default location of ‘root’ is used (‘/’).

You can also read in a dataset and attributes directly after the object has been created:

e = VsHdf5.Particles()array, attrs = e.readParticles('baseName_electrons_1.h5', 'electrons')

In this invocation, array will contain the numpy dataset, and attrs will contain the dictionary of attributes.

Certain objects often only occur once in a given file, such as Limits, Meshes, and RunInfo objects. For these types ofobjects, you can read from a file without specifying the name of the group or dataset that you want to read. VsHdf5will search through the file until it finds a group or object of the correct type, and read it in for you. So you could readthe (single) Limits group in a field file by invoking:

l=VsHdf5.Limits(fileName='gamma2D01_universe_0.h5')

The name of the Limits group in the file is contained in the data memeber

l.name

Required Attributes

Some objects require certain attributes to be VizSchema compliant. Typically, if you read an object from a simulationdump file, then all of the required attributes will be there. You can change individual attribute by using the methods

object.removeAttribute(attName)object.assignAttribute(attName, attValue)

There are additional optional attributes for VizSchema. See the VizSchema documentation and VsHdf5.py docstringsfor more details. The following attributes are required for the objects below. In some cases, there are default values.

278 Chapter 9. Analysis Window

Page 283: VSim In Depth

VSim In Depth, Release 8.2.1

Meshes (Hdf5 Group or Dataset):

Meshes are important types of objects for VizSchema, and deserve more attention here. Meshes may be datasets orgroups in a Hdf5 file, depending on the kind of mesh. Currently, VsHdf5 supports reading and writing of mesh objectscalled StructuredMesh, UnstructuredMesh, UniformCartesianMesh, and RectilinearMesh. Each of these kinds requiredifferent attributes (see below). There is also a generic mesh object that makes it easier to read a mesh from a file. Ifyou invoke:

m = VsHdf5.Mesh(fileName='gamma2D01_nodalE_0.h5')

for instance, then VsHdf5 will search for the (single) group or dataset that is a mesh in the file, will determine the kindof mesh, and will cast itself into that particular kind. So here, for instance, since the gamma2D01 simulation was inCylindrical coordinates (ZR), we find that the mesh object is a RectilinearMesh.

In [5]: m = VsHdf5.Mesh(fileName='gamma2D01_nodalE_0.h5')In [6]: mOut[6]: <VsHdf5.RectilinearMesh instance at 0x104b88170>

Rectilinear Meshes (Hdf5 Group)

meshName Name of the group to be written in the file. Default = objectName

axis0data Dataset representing the coordinates of the mesh in direction 0

axis1data Dataset representing the coordinates of the mesh in direction 1. Required if simulation is 2-Dimensional.

axis2data Dataset representing the coordinates of the mesh in direction 2. Required if simulation is 3-Dimensional.

axis0Name Name of the dataset corresponding to the first axis. Default = axis0

axis1Name Name of the dataset corresponding to the second axis. Default = axis1

axis2Name Name of the dataset corresponding to the third axis. Default = axis2

limits Name of a limits group that gives the spatial limits of the simulation

UniformCartesian Meshes (Hdf5 Group)

meshName Name of the group to be written in the file. Default = objectName

lowerBounds Array of physical coordinates representing the left, bottom, back corner of the simulation domain

upperBounds Array of physical coordinates representing the right, top, front corner of the simulation domain

numCells Array of integers giving the number of computational cells in each direction

startCell Cell index of lowerBounds, default = [0,0,0]

Structured Meshes (Hdf5 Dataset)

meshName Name of the group to be written in the file. Default = objectName

9.5. User’s Guides to help create Analysis Scripts 279

Page 284: VSim In Depth

VSim In Depth, Release 8.2.1

Unstructured Meshes (Hdf5 Group)

meshName Name of the group to be written in the file. Default = objectName

pointsData Dataset of physical coordinates of vertexes of the mesh (reals)

edgesData Dataset of connectivity between vertexes of the mesh (ints)

facesData Dataset of connectivity between vertexes of the mesh (ints)

polygonsData Dataset of connectivity between vertexes of the mesh (ints)

pointsName Name of the dataset containing vertex coordinates. Default = “points”

polygonsName Name of the dataset containing vertex connectivity. Default = “polygons”

Note: Only one of edgesData, facesData, or polygonsData is needed. pointsData is always required.

Fields (Hdf5 Dataset)

fieldName Name of the dataset to be written in the file. Default = objectName

mesh Name of a mesh group that the field is defined upon

limits Name of a limits group that gives the spatial limits of the simulation

timeGroup Name of a time group that indicates the simulation time and step

offset Centering of the data. default = ‘none’

dumpTime Simulation time when the data was dumped. default = 0.0

Histories (Hdf5 Dataset)

historyName Name of the dataset to be written in the file. Default = objectName

mesh Name of a mesh group that the field is defined upon, typically a 1-Dimensional time series

Particles (Hdf5 Dataset)

particlesName Name of the dataset to be written in the file. Default = objectName

charge The charge of the particle species

mass The mass of the particle species

numPtclsInMacro The number of physical particles per simulation particle

limits Name of a limits group that gives the spatial limits of the simulation

timeGroup Name of a time group that indicates the simulation time and step

numSpatialDims Number of spatial dimensions. default = 3

vsNumSpatialDims Number of spatial dimensions. default = 3

dumpTime Simulation time when the data was dumped. default = 0.0

280 Chapter 9. Analysis Window

Page 285: VSim In Depth

VSim In Depth, Release 8.2.1

RunInfo (Hdf5 Group)

runInfoName Name of the group to be written in the file. Default = objectName

TimeGroups (Hdf5 Group)

timeGroupName Name of the group to be written in the file. Default = objectName

dumpTime Simulation time when the data was dumped.

Reading in an entire file

It is also possible to parse an entire VizSchema-compliant file. To do this, invoke:

f = VsHdf5.VsFileReader(fileName=fileName)

This will create an object that contains all of the datasets and groups in the file that have VizSchema attributes. Thisdoes not guarantee that the file is VizSchema compliant however. In particular,

f.objectDict

is a Python dictionary with key equal to the name of the object (Field, Mesh, etc.) and value equal to a VsHdf5 objectof the appropriate type. As with reading in individual objects, the objects in the dictionary will contain both datasetsand attributes as appropriate to the type of object.

Now you can read in a group by calling it’s name explicitly

electrons = f.objectDict['electrons']limits = f.objectDict['globalGridGlobalLimits']

External links

VsHdf5 supports reading and writing of external links from/to files.

To write a link to an external file, use:

object.writeExternalLink(fileName, name, target, location='/')

fileName is the name of the file to write the link into

name is the name of the link in that file

target is the name of the external file that contains the actual dataset or group

Location is an optional parameter that specifies the location of the link “name” in the file “fileName”, in case thisis not the root group.

“object” is any VsHdf5 class

Note that the target file may or may not exist. So for instance, if you invoked:

mesh.writeExternalLink('outVsHdf5.vsh5', 'goodLink', 'ww02_nodalExternalB_99.h5', '/→˓globalGridGlobal')

9.5. User’s Guides to help create Analysis Scripts 281

Page 286: VSim In Depth

VSim In Depth, Release 8.2.1

This would create an external link in the file outVsHdf5.vsh5 called goodLink, that would point to the group /global-GridGlobal in the file ww02_nodalExternalB_99.h5. Subsequently, accessing the Hdf5 node goodLink would be as ifthe group /globalGridGlobal was actually in the file outVsHdf5.vsh5.

To read an external link from a file, simply read it as if it were a group or dataset object in the target file, e.g.

emesh = VsHdf5.Mesh(fileName='outVsHdf5.vsh5', name='goodLink')

will transparently dereference the external link called “goodLink” in the file “outVsHdf5.vsh5”, and create the VsHdf5Mesh object (appropriately cast to the proper type) as if the mesh group was in the file “outVsHdf5.vsh5”. If the linkis broken, namely if it points to a file with a fully qualified path that does not exist, then VsHdf5 will look for a filewith the same name in the current directory. If that file in turn does not exist, or the group or dataset can not be readfrom an existing target file, then an error is reported and the object is not read.

Special Accessor methods

Some attributes are commonly used in analysis scripts, and so they have their own accessor methods. The value of anyattribute can be found by

att = object.attribute(key)

where key is the name of the attribute. If the attribute does not exist in the object, then att = None.

For most objects (dataset and group types), where applicable:

object.getType(): return the value of 'vsType'.object.getKind(): return the value of 'vsKind'.object.getLowerBounds(): return the value of 'vsLowerBounds'.object.getUpperBounds(): return the value of 'vsUpperBounds'.object.getNumCells(): return the value of 'vsNumCells'.object.getStartCell(): return the value of 'vsStartCell'.object.getCentering(): return the value of 'vsCentering'.object.getDumpTime(): return the value of 'time'.

For TimeGroup objects:

object.getTime(): return the value of 'vsTime'.object.getDumpStep(): return the value of 'vsStep'.

For Particles objects:

object.getCharge(): return the value of 'charge'.object.getMass(): return the value of 'mass'.object.getNumPtclsInMacro(): return the value of 'numPtclsInMacro'.object.getNumSpatialDims(): return the value of 'vsNumSpatialDims'.

Writing a VizSchema-compliant file from data

To write VizSchema-compliant data into a file, simply call the VsHdf5 objects write method, such as:

e.writeParticles(filename)

Similarly for fields (writeField), meshes (writeMesh), etc. See below.

Some objects require that certain attributes be defined. In this case, if you try to write the object to a file withoutdefining those attributes, then a warning will be written to stdout and the object will not be written to a file. Similarly,

282 Chapter 9. Analysis Window

Page 287: VSim In Depth

VSim In Depth, Release 8.2.1

if a dataset or group with the same name as the object to be written already exists in the file, it will not be overridden,and a warning will be printed.

If you have created a dataset that you would like to write into a file in a VizSchema-compliant fashion, you can dothis by constructing the needed objects by hand (as opposed to reading them in from an existing file). Consider thefollowing example:

lb=numpy.double(0.)ub=numpy.double(1.)nc=numpy.int(100)ts = VsHdf5.UniformCartesianMesh(name='timeSeries')ts.writeMesh('outputFile.vsh5', lowerBounds=lb, upperBounds=ub, numCells=nc)

array = numpy.zeros(100)d = VsHdf5.History(name='myHistory')d.assignDataset(array)#[add any required attributes, e.g.]d.assignAttribute('vsType','variable')d.assignAttribute('vsMesh','timeSeries')d.writeHistory('outputFile.vsh5')

This will create a file called ‘outputFile.vsh5’ with a 10x10 dataset called ‘myHistory’, with the attributesvsType=variable and vsMesh=timeSeries. Notice that we first created a mesh object that is the 1-Dimensional time se-ries on which the history is defined. Also note that arrays and scalar numerical values that are passed to write methodsmust be numpy objects, not Python lists.

Example of Writing a VizSchema-compliant file from existing data

import VsHdf5

# read in the filef=VsHdf5.VsFileReader(fileName='ECDriftQuad_electrons_1.h5')

#print file contentsprint f.objectDict

electrons = f.objectDict['electrons']limits = f.objectDict['globalGridBlobalLimits']runInfo = f.objectDict['runInfo']timeGroup = f.objectDict['time']

#print time group attributesprint timeGroup.attributeList

#print the dump time and dump step from the time groupprint timeGroup.getDumpTime()print timeGroup.getDumpStep()

#overwrite the attribute "vsStep" with a new value of 1timeGroup.assignAttribute('vsStep',1)

#overwrite the attribute "vsTime" with a new value of 1e-1timeGroup.assignAttribute('vsTime', 1e-1)

#print new time group attributesprint timeGroup.attributeList

9.5. User’s Guides to help create Analysis Scripts 283

Page 288: VSim In Depth

VSim In Depth, Release 8.2.1

#give the name of the new output fileof = 'outfile.vsh5'

#write the new timeGroup data to a file and copy the rest of the file as oldelectrons.writeParticles(of,timeGroup='time')runInfo.writeRunInfo(of)limits.writeLimits(of)timeGroup.writeTimeGroup(of)

9.5.2 TxPyUtils User’s Guide

TxPyUtils Introduction

TxPyUtils is a collection of python classes providing middleware functionality. The most relevant to users of VSim isthe TxOptParse class, for handling the input to analysis scripts and the interaction with the VSimComposer analysistab.

Requirements

TxPyUtils has been developed and is tested using Python 2.7. It is known to work with Python 2.6. It works in theembedded python environment provided by the analysis tab. It depends on the (now deprecated) optparse standardpython module and the readPre module. TxPyUtils in its current form is not compatible with Python 3, due to thedeprecation of optparse.

Usage

TxPyUtils is included in VSimComposer’s embedded python environment. Outside this environment, to use TxPyU-tils, ensure TxPyUtils.py, optparse.py and readPre.py are in your PYTHONPATH. Then simply use:

import TxPyUtils

in your Python script.

Typical usage would involve the setting up of a list of options and passing them to the TxOptParse class:

options = []options.append(('-s','--simulationName','Base simulation name, i.e., the input \

file name without extension.', 'string', None, True))options.append(('-S','--speciesName', 'Name of the species to analyze', \

'string', None, True))options.append(('-T','--threshold','Particle densities below this will be \

ignored','float',None,False))ops = TxPyUtils.TxOptParse(desc=description, ops=options, hasOverwriteOption=True)

If you are using a script written for VSim 7.2 or before, please note that TxOptParse now expects to be told if you donot wish to include an option in your analysis script to overwrite any previous data that it finds with the same filename.You may then read the variables into your script as follows:

baseName = ops['simulationName']speciesName = ops['speciesName']threshold = float(ops['threshold'])overwrite = ops['overwrite']

284 Chapter 9. Analysis Window

Page 289: VSim In Depth

VSim In Depth, Release 8.2.1

For each argument we want to read from the command line or from input boxes in the analysis pane into its script, weset up six options set up for TxOptParse as follows.

parameternumber

parameter purpose example allowed values

1 short argument name ‘-s’ string with a single alphanumericcharacter following a hyphen

2 long argument name ‘–simulationName string starting with two hyphens,no spaces and only alphanumericcharacters

3 description ‘Base simulation name’ any string delimited by singleor double quotes, without escapecharacters

4 argument type, alowsfor limited parsing byour analysis pane

‘string’ ‘float’ ‘int’ only one of those values men-tioned to the left here

5 default value 2, ‘_history’, None See examples. Should be of thecorrect type

6 is value required? True or False (ieBoolean)

Only True or False

Users are encouraged to check the scripts provided by Tech-X for further examples of usage.

This interface is likely to be replaced in future releases of VSim, so please use with care.

9.5. User’s Guides to help create Analysis Scripts 285

Page 290: VSim In Depth

VSim In Depth, Release 8.2.1

286 Chapter 9. Analysis Window

Page 291: VSim In Depth

CHAPTER

TEN

ADVANCED CONCEPTS

10.1 Running Vorpal

10.1.1 Running the VSim Engine (Vorpal) from the Command Line

The following sections describe how to run Vorpal from the command line.

PATH Definitions

It is recommended you set up your definitions/environment variables as follows. Please change as appropriate if youhave installed VSim in a different location.

On Windows (e.g. 64-bit) you can set your path and variables at the DOS prompt (run cmd.exe)

set VSIM_DIR=C:\Program Files\Tech-X (Win64)\VSim-8.1set VORPAL_BIN_DIR=%VSIM_DIR%\Contents\engine\binset VORPAL_LIB_DIR=%VSIM_DIR%\Contents\engine\libset VORPAL_SHARE_DIR=%VSIM_DIR%\Contents\engine\share

One should additionally set the following environment variables:

set PATH=%VORPAL_BIN_DIR%;%PATH%set PYTHONPATH=%VSIM_DIR%\Contents\bin\lib\python;%VSIM_DIR→˓%\Contents\bin\lib\python\lib;%VORPAL_SHARE_DIR%\scripts

Using the embedded VisIt in the path is untested. In the event that you wish to include your own macro files that arenot in the same directory as the simulation input, you may wish to set:

set TXPP_DIR=C:\Users\ThisUser\Documents\txcorp\VSim\macros

VSimComposer will automatically create a similar directory if used.

On Windows the parallel messsage passing interface (MPI) library provided with VSim is MS MPI (from Microsoft).You may wish to put all this in a .bat file for reuse.

On Linux (assuming you have chosen /usr/local/VSim-8.1 as your default installation directory) we encourage you toset

export VSIM_SCRIPT_DIR=/usr/local/VSim-8.1export VSIM_CONTENTS_DIR=$VSIM_SCRIPT_DIR/Contents

On Mac we encourage you to set

287

Page 292: VSim In Depth

VSim In Depth, Release 8.2.1

export VSIM_CONTENTS_DIR=/Applications/VSim-8.1/VSimComposer.app/Contentsexport VSIM_SCRIPT_DIR=$VSIM_CONTENTS_DIR/MacOS

On Linux and Mac

On Linux and Mac, the VSimComposer.sh script in VSimComposer sets several environment variables that enableyour operating system to find the libraries and executables it needs. This is invoked via

source $VSIM_SCRIPT_DIR/VSimComposer.sh

This is a bash shell script, which means you must be running the bash shell to execute the above command. If youare normally a csh/tcsh user, you will need to start up a bash shell to execute the above command and subsequentlyexecute VSimComposer.

Most distributions/operating systems will allow you to add the above command to the .bashrc file in your homedirectory, which will prevent having to run it each time you log in. Note that any changes you make to your .bashrcdo not take effect until the next time you log in, so after modifying your .bashrc file, you must execute the followingcommand in your current shell, but will not need to do it in the future:

source ~/.bashrc

For the discussions below, the following variables will also be assumed to have been set.

export VORPAL_BIN_DIR=${VSIM_CONTENTS_DIR}/engine/binexport VORPAL_LIB_DIR=${VSIM_CONTENTS_DIR}/engine/libexport VORPAL_SHARE_DIR=${VSIM_CONTENTS_DIR}/engine/share

Commonly used environment variables that you can specify in the shell include:

SIM_DATA_PATH Define a list of directories for Vorpal to search data files from, in order to hold a central repositoryfor EEDL, LXCAT and other files. When a data file is needed in a simulation, Vorpal will search it in orderof current directory and all directories listed in SIM_DATA_PATH. One can set up this environment variablebefore running VSimComposer. It defaults to $VORPAL_SHARE_DIR/data.

Vorpal Command Line Options

When running Vorpal from the command line, the input filename and runtime options are specified as command lineoptions. To use multiple options, the command line syntax is:

vorpalser|vorpal -i filename [-o prefix_name] [-dim num] [-dt fnum] [-rnum][-sd] [-nd] [-nc] [-oc] [other options]

in which vorpalser is used to run a serial computation or vorpal for parallel. See Serial Computation fordetails about serial computation. See the Parallel Computation for details of command line invocation with parallelcomputation.

Commonly used options that you can specify on the command line include:

-i filename Read input from file named filename.

For example:

vorpalser -i esPtclInCell.pre

-o prefix_name Base names of output files on the text string prefix_name.

For example, if you want output files named newesPtclInCell rather than esPtclInCell, use:

288 Chapter 10. Advanced Concepts

Page 293: VSim In Depth

VSim In Depth, Release 8.2.1

vorpalser -i esPtclInCell.pre -o newesPtclInCell

-dim num Run simulation using num spatial dimensions. This option overrides the dimension parameter speci-fied in the input file.

For example, if you want to run esPtclInCell in 2D rather than 3D, use:

vorpalser -i esPtclInCell.pre -dim 2

-dt fnum Use time step of size fnum. This option overrides the dt parameter defined in the .pre file.

For example, if you want to run esPtclInCell with the timestep duration 9.9e-12 seconds, use:

vorpalser -i esPtclInCell.pre -dt 9.9e-12

-n num Run the simulation for num time steps. This option overrides the nsteps parameter.

For example, if you want to run esPtclInCell with 50 time steps rather than 10, use:

vorpalser -i esPtclInCell.pre -n 50

-d num Dump data every num time steps. This option overrides the dumpperiodicity parameter.

For example, to run esPtclInCell and dump output after every 5 time steps, use:

vorpalser -i esPtclInCell.pre -d 5

-r num Restart Vorpal from dump num.

For example, if you want to restart esPtclInCellSteps using the output dumped at time step 50, use:

vorpalser -i esPtclInCellSteps.pre -r 50

-sd Dump data at start of simulation. This option is useful for debugging purposes. It lets you see whether Vorpalused the data you wanted it to use at the start of the simulation.

-nd Disable data dumping.

-nc Redirect all of the *_comms_*.txt output to /dev/null.

-oc [rank] Suppress the creation of all comms text files except for that file from the specified [rank] process. Thisflag is overridden by the -nc flag, above.

-b Provide a barrier at each timestep. This means that when running in parallel at the end of a timestep the simulationwill halt all processes that are more rapid than other so that the slower processes can catch up before the nexttimestep initiates.

-id Forces each processor to dump into its own separate file, these files can then be concatened into a single file foranalysis.

-ns Disable particle sorting. Sorting affects the way particles in cells and memory are handled and can lead to soinefficiencies both with sorting on or off, it is up to the user to discover whether or not to turn the sorting off.However, there are some algorithms especially in the plasma discharge realm in which sorting is needed.

-gpudevnum Select the GPU to use to run a serial run.

-ra Read all particles from all domains on a restart. Particularly useful if you try to restart with a different numberof cores or configuration of domains to the dataset from which the earlier data is taken.

-v, --version Show vorpal version. This provides information relevant to developers if you run into issues.

-validate Validate input file semantics.

10.1. Running Vorpal 289

Page 294: VSim In Depth

VSim In Depth, Release 8.2.1

-svn, --svn Show svn revision number of this build.

--license Show license info.

-iargs Pass options (including substitutions) to internal txpp. For example:

vorpalser -i esPtclInCell.pre -iargs NDIM=2, DX=0.1

Order of Parameter Precedence

If a parameter is both set within the input file and specified on the command line, the command line parameter valuetakes precedence. The command line override enables you to configure an input file with default values while exploringalternative parameter settings from the command line. From the command line, you can quickly change simulationrun lengths, dimensionality, output timing, etc.

Serial Computation

The Vorpal executable for use in serial computation is named vorpalser. Except as noted, the explanations andtutorials within the VSim In Depth and vsim-quick-start demonstrate Vorpal usage for serial computations. Here isan example of Vorpal command line invocation using an input file named myfile.pre and specifying 1000 timesteps, outputting the result data (dumping) every thousand steps. By default, the output files for this example wouldbe named using the format myfile.out.

vorpalser -i myfile.pre -n 1000 -d 1000

Note: The above invocation line assumes you added VORPAL_BIN_DIR to your PATH, as noted above.

Note: When running Vorpal via VSimComposer, command line options are available under the Advanced tab onthe Runtime Options page in the Additional arguments text box. However, -i and -o command line optionsdescribed in this document are implicit; that is, these options are automatically invoked when running VSimComposer.

The Vorpal computation engine for serial computations also creates a single text file named myfile_comms_0.txtunless this has been suppressed by command line or input file options.

Parallel Computation

The Vorpal executable for use in parallel computation is named vorpal. This section explains use of the Vorpalexecutable program for parallel computations.

Vorpal for parallel computations requires the Message Passing Interface (MPI). On Mac and Windows you must useour bundled MPI. On Windows the parallel messsage passing interface (MPI) library provided with VSim is MS MPI(from Microsoft). On Mac the parallel messsage passing interface (MPI) library provided with VSim is OpenMPI. OnLinux the parallel messsage passing interface (MPI) library provided with VSim is Mpich. If there is a reason whyyou must use a system MPI, please contact Tech-X support, who will quote you for a custom installation.

For administrator information about MPI for use with Vorpal, see Advanced Job Script and Queue Configuration.

290 Chapter 10. Advanced Concepts

Page 295: VSim In Depth

VSim In Depth, Release 8.2.1

Parallel Computation Scripts

Running Vorpal with MPI either directly or Parallel Queuing Systems requires use of different shell scripts to enableinvocation of the Vorpal executable as discussed in the following sections.

• Running VSim’s vorpal engine directly, and instantly on the local machine: Running Vorpal with mpiexec.

• Running vorpal instantly on nodes of a cluster that’s not running a resource scheduler (possibly including thelocal machine): Running Vorpal with mpiexec using a hostfile.

• Running vorpal through a resource scheduler (queue system) on linux: Running the VSim Engine (Vorpal) froma Queuing System.

• Running vorpal through Windows HPC Cluster Pack: Running Vorpal under Windows HPC Cluster.

Running Vorpal with mpiexec

In order to run Vorpal in parallel via the command line, you must first add the <VORPAL_BIN_DIR> to your PATH,as noted in the user-guide-running-vorpal-from-the-command-line-command-line-path section.

To run Vorpal in parallel, execute the following command:

mpiexec -np <#> vorpal -i filename

in which <#> is the number of processors, vorpal is the executable program for parallel computations, andfilename is the name of the input file (which must be in the current directory, or must be specified by a fullpath).

Following mpiexec, but before vorpal, you can specify a variety of mpiexec options. For more informationabout mpiexec, including the complete list of options, see a man page or other documentation for mpiexec.

Following vorpal, you can specify a variety of Vorpal options. For a list of commonly used options, see VorpalCommand Line Options.

Vorpal automatically adjusts its decomposition to match the number of processors it is given, unless a manual decom-position is provided for the correct number of cores in the input .pre file.

In contrast to Vorpal for serial computation, which creates a single output file, Vorpal for parallel computation createsmultiple output files. Each individual processor from the parallel run sends comments to a different output file. Aparallel computation output file’s name includes a label that identifies the number of the processor that generated thatfile, for example:

• esPtclInCell_comms_0_1.txt

• esPtclInCell_comms_0_2.txt

in which the final _0 and _1 before the file name suffix indicate the number of the processor.

Running Vorpal with mpiexec using a hostfile

The following instructions are written assuming a linux command line structure. The path and directory structuresshown will simply need to be altered to those of Mac above in PATH Definitions if necessary. Parallelism withwindows is supported on with Windows HPC cluster as described in Running Vorpal under Windows HPC Cluster.

If the you need to run an MPI job but do not have access to a queuing system then a hostfile must be set up. If this isthe case you must know the node names on the cluster that the job is to be run on. You must then create a text file withyour text editor of choice, this is your hostfile, and place it in your home directory. The hostfile simply contains each

10.1. Running Vorpal 291

Page 296: VSim In Depth

VSim In Depth, Release 8.2.1

node name repeated on a new line as many times as there are threads in that node. For example consider a two nodecluster with four threads each, the hostfile will contain

node1node1node1node1node2node2node2node2

To run a job one must then source VSimComposer shell script using the command:

. <VSIM_SCRIPT_DIR>/VSimComposer.sh

You are now ready to run in MPI using the mpiexec command along with the –hostfile option, an example is givenhere:

mpiexec --hostfile /homedir/subdirs/hostfile -x PYTHONPATH -x PATH -x LD_LIBRARY_PATH→˓\-x PYTHONHOME --np numnodes vorpal -i simulationname.pre

The -x options tell the mpiexec command to use the specific environment variables that were set when you sourcedComposer above. The numnodes simply refers to the number of processors that the job is to be run on. Note that if youassign a value to numnodes that is in excess of the number of processors on the cluster the job will fail. Vorpal refersto the engine used to perform the simulation, for a description of the vorpal engine options see Vorpal Command LineOptions

10.1.2 Running in Parallel from VSimComposer

VSimComposer runs simulations in serial by default. If you are running on a local system with multiple cores, youcan run your simulation in parallel as multiple processes.

Permanently Switching the Engine to Parallel Execution

In order to run in parallel, you must first change the engine that VSimComposer is using. To do this, go to VSimCom-poser -> Preferences on Mac OS X, or on Linux/Windows go to Tools -> Settings. This will bring up a pop-up menu.Choose Host Settings from the left menu, click on the MPI tab, and under Preferred run method choose Parallel(MPI) and select your desired Preferred number of cores. See Switching on parallel execution in the settings tab..

Defining the Number of Processors From the Run Window

It is also possible to switch the number of processors to run on a simulation session basis in the Run window. In theupper- right portion of the Runtime Options pane, there is a tab for the MPI. Here you can define the number to as fewor many processes you want to run. If the Run with MPI button is unchecked the simulation will run in serial mode.This setting will be retained for as long as the current file is open. See Changing number of cores on a per-simulationbasis.

Now change any command line options as desired or run as usual by pressing the Run button.

292 Chapter 10. Advanced Concepts

Page 297: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 10.1: Switching on parallel execution in the settings tab.

Fig. 10.2: Changing number of cores on a per-simulation basis

10.1. Running Vorpal 293

Page 298: VSim In Depth

VSim In Depth, Release 8.2.1

10.1.3 Running the VSim Engine (Vorpal) from a Queuing System

Queuing systems, such as LoadLeveler, LSF, SGE and PBS, require the submission of a shell script with embeddedcomments that the systems interpret.

PBS/Torque/OpenPBS

Here is an example of a basic shell script for a PBS-based system. You might call this vaclaunch.pbs:

#PBS -N NDS_vorpal#PBS -l nodes=2:ppn=2export VSIM_DIR=$HOME/VSim-8.1source $VSIM_DIR/VSimComposer.sh batchcd /directory/containing/your/input/filempiexec -np 4 vorpal -i vaclaunch.pre -n 250 -d 50

Sun Grid Engine (SGE)

Here is another example, this time for a SGE (Sun Grid Engine) job, saved as magnetronTest.qsub:

#$ -cwd -V#$ -l h_rt=0:10:00#$ -l np=16#$ -N magnetronTestexport VSIM_DIR=$HOME/VSim-8.1source $VSIM_DIR/VSimComposer.sh batchmpiexec -np 16 vorpal -i magnetron2D.pre

This time the -cwd -V tells the queue system to use the current working directory for the job, and to import the currentenvironment and make this avialable for the script.

The -l commands relate to the resource requirements of the job. In the first (PBS/torque) case, we explicitly specifiedthe number of cores per node, and number of nodes, so we have a total of four MPI ranks on which to execute the job,which is mirrored in the mpiexec -np argument.

The -x option to mpiexec allows one to pass environment variables to each of the Vorpal processes started bympiexec. The environment variables used in the above examples are specifically modified as a result of source$VSIM_DIR/VSimComposer.sh batch command above and may be needed by your simulation.

In the second (SGE) case, the queue system calculates the configuration based on my choice of 16 cores. On thatcluster it is necessary to specify the run duration, which, in this example, is set to 10 minutes.

Platform LSF

Here is a third example, for the Platform LSF system:

#BSUB -o EBDP-VSim8.1.out#BSUB -e EBDP-VSim8.1.err#BSUB -R "span[ptile=16]"#BSUB -n 32#BSUB -J testVSim8.1#BSUB -W 45cd $HOME/electronBeamDrivenPlasmaexport VSIM_DIR=$HOME/VSim-8.1source $VSIM_DIR/VSimComposer.sh batch

export MYJOB=electronBeamDrivenPlasma.pre

mpiexec -np 32 vorpal -i ${MYJOB}

294 Chapter 10. Advanced Concepts

Page 299: VSim In Depth

VSim In Depth, Release 8.2.1

With this submission system and job scheduler, -W is used to denote the wall time for the job in minutes. The name ispassed by -J.

Sometimes one must reference a specific project for accounting purposes in the job submission file. For this you mayuse the -A option.

Slurm

Here is an example from a Cray system with a custom vorpal build running from a directory /project/nnnnn/gnu-5.2.40.

#!/bin/bash#SBATCH --account=nnnnn#SBATCH --job-name=lpa#SBATCH --output=lpa.out#SBATCH --error=lpa.err#SBATCH --nodes=2#SBATCH --time=00:05:00srun --ntasks=1 --hint=nomultithread --ntasks-per-node=1 /project/nnnnn/gnu-5.2.40/→˓vorpal-exported/bin/txpp.py laserPlasmaAccel.presrun --ntasks=32 --hint=nomultithread --ntasks-per-node=16 /project/nnnnn/gnu-5.2.40/→˓vorpal-exported/bin/vorpal -i laserPlasmaAccel.in -n 100 -d 20

Often you would submit these files with qsub vaclaunch.pbs or qsub magnetronTest.qsub, though the command issometimes different on other systems. The moab scheduler often uses msub vaclaunch.pbs, and Platform LSF oftenrequires #BSUB in place of #$ or #PBS. One submits then with bsub < myjob.lsf. Slurm needs squeue job.slurm

Contact your system administrator for advice with the queue commands to use on your system.

10.1.4 Advanced Job Script and Queue Configuration

Starting with VSim 8 we have switched to distributing MPICH-3.1.4. We included version 1.6.5 of openmpi in ourprevious VSim 7.0.0 distribution for linux. This should not affect any other MPI installations as it is self-containedinside our distribution. Note, however, that we recommend that users who wish to run VSim from the command linefirst source ‘VSimComposer.sh’ which is at the top level of the installation, suffixed with batch if they are runningfrom within a batch environment. (This is the script one would normally run to launch our GUI.) Source-ing VSim-Composer.sh will put the Tech-X distributed mpiexec in the user’s PATH, which is needed to run VSim. If the userlater wishes to run something on your cluster which requires a different MPI, then he or she should adjust the PATHaccordingly. But otherwise, there should be no issues with both versions on your system.

There are various ways VSim users may choose to switch between MPI versions.

• give full path to VSim’s mpiexec in qsub script

• create a wrapper script that sits next to VSimComposer.sh and that script would invoke mpiexec

• add source .../VSimComposer.sh (or equivalent export PATH/PYTHONPATH commands) to .bashrcand create an alias to switch back and forth between our mpiexec and the cluster’s.

Occasionally it may be possible to substitute VSim’s MPI libraries for compatible libraries already present ona system. Skilled system administrators will need to remove Tech-X distributed MPICH libraries and ensureLD_LIBRARY_PATH picks out the replacement libraries. We do not recommend or support this. Tech-X is ableto offer VSim compiled against MPI libraries of different versions and from different vendors. To discuss pricing forthis service please contact [email protected].

10.1.5 Running Vorpal under Windows HPC Cluster

When running under Windows HPC Cluster tools, one must modify the above procedure to take into account that onemust run mpiexec through another application, sigcapture.py, which is distributed with VSim, in order to have a clean

10.1. Running Vorpal 295

Page 300: VSim In Depth

VSim In Depth, Release 8.2.1

shutdown. The way to do this is illustrated in the batch file, winClusterSubmit.bat, that is in the Contents/engine/bindirectory. One can use this file, but one must first modify the enviroment parameters, INST_DIR and SIM_DIR, atthe top, the desired output file names, the number of processors, and the name of the input file that you wish to run.After making the appropriate modifications, one can simply run that batch file, e.g.,

> winClusterSubmit.bat

The output will show the full job submit command that was issued. Doing job cancel <jobnum>, where<jobnum> is the numbe of the job, will now result in a clean shutdown, cleaning up the token file and doing a dumpbefore quitting.

10.1.6 Running a Parameter Sweep in VSim/Vorpal

VSimComposer

There is currently no way to run a parameter sweep in VSimComposer, the GUI interface to Vorpal, aside doing onerun, manually changing the parameter in your input file, and running again.

Vorpal / command line

By running on the command line, one can run a parameter sweep by creating a script (.bat file for Windows or .sh filefor Linux/Mac).

After following the instructions in Running the VSim Engine (Vorpal) from the Command Line, you should be able torun on the command line. The argument -iargs can be used to pass a parameter value to your input file for running.

vorpalser -i myFile.pre -iargs FREQUENCY=1.e9

If you are content with running one file at a time (eg for relatively quick simulations, or where all simulations scaleperfectly onto all the cores you have available), the quickest way to scan through a set of frequencies, for instance, onecould write a script (.bat or .sh) to loop over the values.

Linux/Mac

A basic example to loop through a number of wavelengths (2-10 by steps of 1) in the emPlaneWave example is asfollows:

for number in `seq 2 1 10` ; dovorpalser -i emPlaneWaveT.pre -iargs WAVELENGTHS=$number -o emPlaneWaveT_${number} \> emPlaneWaveT_${number}.log

done

Windows

A basic example to loop through a number of wavelengths (2-10 by steps of 1) in the emPlaneWave example is asfollows:

FOR /L %n IN (2,1,10) DO vorpalser.exe -i emPlaneWaveT.pre -iargs WAVELENGTHS=%n \-o emPlaneWaveT_%n > emPlaneWaveT_%n.log

In a batch file, use %%n in the above command.

296 Chapter 10. Advanced Concepts

Page 301: VSim In Depth

VSim In Depth, Release 8.2.1

Advanced Bash (Linux/Mac/Cygwin)

If you purchased a license that allows you to run multiple cores at the same time, you may wish to take advantage of itfully here. One may run each of the jobs above in parallel, or you may want to run ‘task parallel’ jobs, so that multipledifferent points in the sweep are being carried out concurrently. This is particularly useful in conjunction with queuesubmission.

Additionally you may want to use VSimComposer for visualisation after the simulation is complete, which requiresyou to have the .pre file in the run directory, and one directory per simulation. The script below was written for acygwin machine with four cores. One core was kept clear so that the machine did not slow too much. Please note,the wc ... | cut -f2 -d" " approach will not work for larger core counts as the format of wc will change ifthere are more characters. The awk command is pretty standard and would be better. This is principally to provideinspiration if you wish to do something more complex. If you have comments and suggestions please email technicalsupport.

waitForLicense() {# checks that we are not using more than a certain number of instances# give the previous vsim instance a minute to spin up.

sleep 3if [ -z /cygdrive/c/ProgramData/Tech-X/Vorpal7/tokenfile ]; then echo; echo

→˓"TokenFile Empty"; echo; vsimInstances=0; fivsimInstances=`wc /cygdrive/c/ProgramData/Tech-X/Vorpal7/tokenfile | cut -f2 -d"

→˓"`echoecho "${vsimInstances} instances of VSim are checked out, max is ${maxInstances},

→˓checking... "echowhile [ ${vsimInstances} -ge ${maxInstances} ]do

echoecho "${vsimInstances} instances of VSim are checked out, waiting a minute

→˓because maximum is ${maxInstances}"sleep 60if [ -z /cygdrive/c/ProgramData/Tech-X/Vorpal7/tokenfile ]; then echo

→˓"\n\nTokenFile Empty\n\n"; vsimInstances=0; fivsimInstances=`wc /cygdrive/c/ProgramData/Tech-X/Vorpal7/tokenfile | cut -f2 -d

→˓" "`echoecho "${vsimInstances} instances of VSim are checked out, max is ${maxInstances}

→˓, checking..."echo

done}

runAtVolt() {mkdir -v ${volt}V${decorator}cd ${volt}V${decorator}echo "removing existing files from dir ${volt}V"rm ${filebasename}${volt}V*cp ../../parPlatesSphereBeamSphereParameters50cells.pre ./${filebasename}${volt}V$

→˓{decorator}.prewaitForLicensevorpalser -sd -i ${filebasename}${volt}V${decorator}.pre -iargs USE_PYRAMIDS=1,USE_

→˓SPHERES=0,BEAM_ENERGY_IN_EV=${volt}.,ANGLE_TAN=0.001,NX=${resx},NY=${rest},NZ=$→˓{rest},V_RIGHT=${bias},BEAM_ANGLE_DEGREES=${angle},NUM_PHYSPTCLS_PER_MACRO=.4,CALC_→˓FIELD_PERIOD=250 &cd ..

}

10.1. Running Vorpal 297

Page 302: VSim In Depth

VSim In Depth, Release 8.2.1

export PATH=/cygdrive/c/Program\ Files/Tech-X\ \(Win64\)/VSim-7.2/Contents/engine/bin/→˓:$PATH

export vsimInstances=0 # rely on wc to set vsimInstances if there are already any→˓running.export maxInstances=3

export filebasename="pyrAngle"export bias="-.9"export resx="100"export rest="60"export decorator="B09Rx100t60"for volt in 200 75 25 50 100 150 250 300 400 500do

runAtVoltdone

export bias="-.6"export decorator="B06Rx100t60"for volt in 200 75 25 50 100 150 250 300 400 500do

runAtVoltdone

10.1.7 GPU Computing

GPU Computing: VSimEM is capable of performing computation on NVIDIA GPUs (Graphical Processing Units).In order to use these features, your system must have a CUDA capable GPU and the appropriate nvidia drivers(version >352.00). Provided certain criteria are met in terms of simulation size, GPU-accelerated pure Electro-magnetic simulation can achieve substantial speedup over parallel (multi-core) CPU simulations. Moreover, thisbenefit can be quite significant if your simulation requires complex space-time transformations of the Electricand Magnetic fields or your simulation has complex driver source functions for the current fields.

In the current release, VSim only supports three-dimensional (3D) pure Electromagnetic simulations.

Domain Size Considerations

Due to the nature of the underlying data structure and its effect on the performance of the computations, one needsto pay special attention to the simulation size. In particular, one typically wants to set the number of cells (includingguard/halo cells) in the z-direction to a multiple of 64 (128) in double (single) precision for the NVIDIA C2070 (Fermi)architecture. For example, one might choose a simulation with 62 (126) cells in the z-direction. The additional guardcell above and below the physical domain yields 64 (128) total cells in the z-direction. By default, VSim uses a datastructure for the GPU that ensures aligned memory accesses (through padding). This is essential for achieving highmemory bandwidth on the device. However, insisting that domains have a multiple of 64 (128) cells in the z-directionforces all threads in a block to be active. This also ensures efficient utilization of device resources.

However, one must take care not to make simulations too big. Currently, there is a limit of 65536 cells in the x and ydirections and 8192 cells in the z-direction on some Nvidia GPUs. Although some more recent Nvidia GPUs can dolarger simulations in those directions. One should be aware that sufficient device memory is necessary to fit all of thedata for the fields on the device (that is, we do not swap data between the host and the device). In order to determinethe maximum simulation size, we use the formula:

𝑁𝑓 ×𝑁𝑐𝑒𝑙𝑙𝑠 × 𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛 < Device Global Memory

298 Chapter 10. Advanced Concepts

Page 303: VSim In Depth

VSim In Depth, Release 8.2.1

𝑁𝑓 = Number of Fields (including components)

𝑁𝑐𝑒𝑙𝑙𝑠 = Total Number of Simulation Cells Per Field (including Guard Cells)

𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛 = 8(4) for double (single) precision

As an example consider a cavity simulation with a current source driver, to be executed in double precision on anNVIDIA C2070 GPU. This simulation has 5, 3-component fields for E, B, J, L, and A–L and A are the Dey-MittraGeometry descriptors which are represented as 3-component fields on the GPU. A C2070 has ~6 GB Device Memory,however in practice, we have found that roughly 5GB or less is accessible in a computation. Then.

15 × 8 × (4.𝑒7𝑐𝑒𝑙𝑙𝑠) ≈ 4.5𝐺𝐵

Thus, about 40 million cells (including guard/halo cells) is the upper limit for the size of the simulation that can fitonto a single C2070 for double precision.

To learn more details on the capabilities of your device, run vorpal with the command line flag

-gpuinfo

For the C2070, the following will be printed to standard out of your simulation.

GPU_Initialize::cudaGetDeviceCount() detects 1 devices available to rank 0GPU_Initialize::cudaSetDevice() setting local GPU device #0 on rank 0GPU_Initialize::deviceProperties for device #0 are :

name=Tesla C2070compute capability=2.0totalGlobalMem=5.24921 GB

The last print statement is critical since the number of pitched cells can change between different GPU models. Thus,users should inspect this diagnostic and then restructure simulation parameters accordingly.

Parallel GPU Simulations

In the event that your simulation size exceeds the memory on a single device or you want to accelerate your com-putation with a multi-GPU simulation, the VSim product offers GPU capabilities that are supported on parallel-GPUmachines, i.e. systems or clusters with multiple GPUs. Since every system configuration is different with regard tothe number of GPUs per node, it is difficult to give an exact recipe of how to run your simulations in parallel. It isuseful to illustrate with a few examples. On a single node desktop machine with two GPUs, simply using mpiexec-np 2 will ensure that both GPUs are used in a parallel simulation. On a machine cluster such as DIRAC at NERSC,where many of the nodes have 1 GPU per node (8 cores), one would run with 1 core per node on N nodes to do an NGPU simulation.

In particular, one should never run parallel GPU simulations where the number of MPI ranks per node, exceeds thenumber of GPUs. Indeed, one has to match these numbers exactly.

In general, there are strategies for maximizing the performance of a parallel GPU simulation. In particular, one wantsto avoid general domain decomposition as this can have an adverse effect on the performance. Ideally, one shoulddecompose only in the x-direction as this is the slowest varying dimension in the data structure. It should be noted thatgeneral domain decomposition is supported.

Supported Features

VSimEM features GPU equivalents of many CPU macros. This allows for a simulation to be run on a GPU withminimal changes to the input file. These macros include, Antennas, Dielectric, Far Fields, Geometry, mal, ScatteringBox, and with a slightly more limited functionality, Yee.

10.1. Running Vorpal 299

Page 304: VSim In Depth

VSim In Depth, Release 8.2.1

VSim GPU updaters consist of Yee Electromagnetics (gpuAmpereUpdater, gpuFaradayUpdater),Electromagnetics with embedded boundaries using Dey-Mittra models (gpuDeyMittraFaradayUpdater,gpuGeometryUpdater), as well as linear plasma calculations (gpuLinPlasDielcUpdater). There alsomany auxilliary updaters for enabling complex user-defined simulations. One very powerful updater is the spacetime function updater (gpuSTFuncUpdater). This updater allows user functions to be calculated on the GPU.Other useful updaters include the binary updater (gpuBinaryUpdater) which allows gridded fields to be com-bined according to some binary operation, unary updaters (gpuUnaryUpdater) which enable unary opera-tions to gridded fields, and the linear apply updater (gpuLinearApplyUpdater), which allows one to douser defined sparse-matrix vector multiplications. This last updater is particularly powerful as it allows for arbi-trary, user-defined stencil operations on gridded-field quantities although constructing the matrices requires somecare. Additional updaters include the gpuResetUpdater, gpuCopyUpdater, gpuEdgeToNodeUpdater,gpuEMOpen, gpuFieldSquaredUpdater, and gpuGradUpdater. All CPU based boundary, initial, andsource conditions are supported for GPUs. This includes conducting, periodic, copy, and open (out going wave)boundary conditions. Lastly, field-based history computations are supported including kirchhoff surface integrals,pseudopotentials, and point histories like fields at specified indices or coordinates.

Example Simulations

Many VSimEM examples feature runtime selectability of GPU computation. No changes to the input file are necessaryother than to import GPU versions of the relevant macro.

These examples include: Advanced Dipole Above Conducting Plane, Dielectric Scattering, Ground Penetrating Radar,Patch Antenna, Patch Antenna Far Field, Predator Drone and Radar Cross Section.

10.1.8 Running on a Remote Host

VSim allows the user to run on a remote host or through a queue system if desired. This is potentially beneficial forseveral reasons, including runs with large data sets, running on a large cluster, or shared resources.

In the present version we offer the following capabilities:

• One may use an external utility to copy the remote files back to a local machine (scp or winSCP are the likelyalternatives). Providing the .pre or .sdf file is in the current directory it should be possible to visualize the outputlocally. This is the most appropriate solution for those dealing with small datasets.

• X Windows: If one does not have hardware acceleration on the remote machine one may forward X using anssh client (ssh -Y) or use accelerated X forwarding using software like NoMachine NX. As of this writing, agood discussion is at X11 Forwarding. Briefly,

– Linux users running X: edit /usr/bin/Xorg as described at the above link.

– OS X users running XQuartz: execute

defaults write org.macosforge.xquartz.X11 enable_iglx -bool true

– Windows users: many options described at the above link.

• VNC: One may try to connect to the remote machine using VNC. One will need to set the environment variableLIBGL_ALWAYS_INDIRECT=1.

• Virtual GL: If one is using a remote machine that has virtualGL server or DCV one may run using the hardwareacceleration on the remote machine. This may provide the best performance but also the most system adminis-tration work Many HPC centers are already set up for this kind of access. There is a super-accelerated virtualGLclient, but it is more common to find virtualGL set up like DCV such that the remote machine is running a VNCserver, which you may connect to with any VNC client on your local machine.

• Use standalone VisIt and it’s remoting feature. VisIt may be downloaded from VisIt. Users of native VisItshould be sure to make sure their local version number (eg 2.11) matches up with the version running remotely.

300 Chapter 10. Advanced Concepts

Page 305: VSim In Depth

VSim In Depth, Release 8.2.1

This option offers the full flexibility of VisIt, such as the ability to make all the individual images needed tomake movies in a single go and the ability to fully python script your visualisation, but there is a correspondinglearning curve. There are many tutorials and resources at The visitusers website.

• Use matplotlib or alternative software on the remote machine. The VsHdf5 module is provided with VSim andmay be used to read and manipulate remote datasets for this purpose.

10.2 Advanced Simulation

10.2.1 Advanced Topics in Electrostatic Simulation

Electrostatic Solvers and Pre-Conditioners

Tech-X offers the following advice on choosing an electrostatic solver, tolerance, and a pre-conditioner.

Choosing an Electrostatic Solver

Due to the way the boundary conditions are implemented in the electrostatic solver, the matrix in the resulting linearsystem is non-symmetric (except for the fully periodic case). Therefore, you should select a solver that can deal withnon-symmetric matrices. The multi-grid pre-conditioned bicgstab solver tends to yield good convergence.

When choosing a solver for periodic problems, the key is to choose a solver that uses at least one boundary conditionto set the potential (define ground). Alternatively, you can use a multigrid pre-conditioner with the bicgstab solver.

Choosing the Tolerance

Many of the parameters in the electrostatic solver are highly problem dependent. The tolerance, which is a measureof the residual reduction compared to the initial residual, is the stopping criterion for the iterative solver. Values of10^{-5} often are sufficient for giving meaningful results. If the solver does not converge, increase the tolerance. Ifthe resulting potentials miss a lot of small scale structure, reduce the tolerance.

Choosing a Pre-Conditioner

Pre-conditioners transform the linear system used in the Poisson solver into systems with more favorable convergencebehavior. For a simple fully periodic system, a pre-conditioner may not be necessary. For most other cases, using apre-conditioner significantly improves the convergence behavior. Multi-grid pre-conditioning tends to yield the bestconvergence behavior.

For a comparison of different pre-conditioners and solvers that you can use for your electrostatic simulations, see P.Messmer and D.L. Bruhwiler, A parallel electrostatic solver for the Vorpal code, Computer Physics Communica-tions, vol. 164, pp. 118-121, 2004.

Putting Mathematical Expressions in an Input File

You can put mathematical expressions directly in an input file’s blocks by encapsulating them between dollar signs $$. When you validate an input file, the expression’s within the dollar signs are evaluated

In the esPtclInCell.pre file, one of the variable definitions is: $NX1 = NX + 1, and several boundary condi-tion input blocks use the NX1 variable in the vector defining the upper bounds. For example: [NX1 0 0]. You canuse a mathematical expression in place of the NX1 variable. For example, you could define the vector as follows: [$NX +1$ 0 0].

10.2. Advanced Simulation 301

Page 306: VSim In Depth

VSim In Depth, Release 8.2.1

Multiplying NX by 2 would also work: as shown here: [$2 * NX + 1$ 0 0].

Saving the Potential to a File

By default, the potential is not written out to a .h5 file. You can save the potential to a file by setting the electrostaticsolver parameter in the <Solver> block:

dumpPotential = true

Symmetry Boundaries

A Neumann boundary can act as a symmetry boundary. For instance, placing Neumann boundaries appropriately onthree faces of a cube will turn the simulation into a symmetric simulation of 1/8th of a larger cube.

Fully Periodic Systems

You can model a system that is periodic in all directions, that is, which has no boundaries. In a fully periodic system,however, the overall charge must be zero as demonstrated in this equation:∫ 𝑥+𝐿

𝑥

𝜕𝐸

𝜕𝑥𝑑𝑥 = 𝐸(𝑥 + 𝐿) − 𝐸(𝑥) =

1

𝜖0

∫ 𝑥+𝐿

𝑥

𝜌𝑑𝑥 =𝐿

𝜖0⟨𝜌⟩ (10.1)

where ⟨𝜌⟩ is the average charge density over the integration interval. Zero net charge can be enforced by specifyingthe electrostatic solver parameter enforceZeroNetCharge = true.

For more information, see Birdsall and Langdon, Plasma Physics via Computer Simulation.[1]

Secondary Electrons

To learn how to add secondary electrons, see the multipacting examples in the VSimMD: Microwave Devices examples,accessible through VSimComposer.

10.2.2 Advanced Topics in Electromagnetic Simulation

Modeling a Time-Dependent or Space-Dependent Value on a Boundary

An electromagnetic boundary condition may use time signals or spatial profiles. For example, the emPlaneWave.pre file’s xLowerWaveLauncher boundary condition input block uses a spatial profile: kind = variable.

The function parameter in a boundary condition input block also may be an expression, and the expression may beany standard function of space and time.

The emPlaneWave.pre file uses the kind = expression technique.

<BoundaryCondition xLowerWaveLauncher># Value given by functionkind = variablelowerBounds = [0 0 0] # Lower limitsupperBounds = [1 $NY+1$ $NZ+1$] # Upper limitscomponents = [1] # Ey polarized<STFunc component1>kind = expressionexpression = 1.e6*sin(OMEGA*t)

302 Chapter 10. Advanced Concepts

Page 307: VSim In Depth

VSim In Depth, Release 8.2.1

</STFunc></BoundaryCondition>

For the complete content of the emPlaneWave.pre file, see the example Electromagnetic Plane Wave in VSimBase.

Creating a Circularly Polarized Pulse

The steps to create a circularly polarized pulse are:

1. In the electromagnetic boundary condition input block, change the components parameter vector to launch botha y and z component: components = [1 2]

2. Give the amplitudes parameter vector a value for each component: amplitudes = [AMPLITUDEAMPLITUDE]

3. Give the phases parameter a value for each component. To make a circularly polarized pulse, the phases for thetwo components should be 𝜋/2 radians (90 degrees) apart: phases = [0. 1.57]

The widths parameter controls the spatial extent of the wave.

Launching a Wave from X-Upper Boundary of Simulation

The steps to change a wave launcher from the x-lower to the x-upper boundary follow:

1. Change the lower and upper bounds of the wave launcher boundary condition to the x-upper end of the grid.

Note: The lower bounds of a boundary condition at the x-upper end of the grid are in the physical domain.

2. Adjust the x-upper conducting boundary to zero out only the y component.

3. Adjust the x-lower conducting boundary to zero out both y and z components. Be sure to change both theamplitudes and components vector.

The simulation occurs in the lab frame. This means the pulse will strike the x-lower boundary and reflect back afterroughly fifty steps for the given time step and simulation size. To avoid reflections, you need to include an absorbingboundary at the x-lower end.

Simulating a Non-Vacuum

To simulate a non-vacuum, see the VSimEM example Photonic Crystal Waveguide, photonicCrystal.pre,accessible through VSimComposer, which demonstrates how to use a dielectric.

Defining Multiple Electromagnetic Fields

Multiple electromagnetic fields can co-exist in a simulation. For more information, see the vsim-reference. Thisfeature is also demonstrated in the VSimEM example, Patch Antenna.

10.2. Advanced Simulation 303

Page 308: VSim In Depth

VSim In Depth, Release 8.2.1

10.2.3 Advanced Topics in Particle Simulation

Particle Tracking

Since VSim is a particle-in-cell code, the position of a specific particle in the particle data structure will vary as thesimulation proceeds due to sorting and the creation and/or deletion of particles. Before you can track a particle, youmust identify the particle by tagging it.

Note: To track an individual particle, you must use a kind of particle species that enables tagging ofindividual particles. Creating a species with the kind parameter set to one of the following kinds enablesyou to create tagged particles that you can then use to generate particle position data for all tags (indicatingup to some maximum tag value) by using History.

• relBorisTagged

• relBorisVWTagged

• relBorisVWScale

Before particles can be tracked they must be tagged. There are four ways to tag particles.

• By setting the tags manually with the manualSrc.

• By using the tagGen STFunc in the funcVelGen VelocityGenerator. See velocity-generator-details.

• By using the fieldScaleVelGen VelocityGenerator. This should only be used withrelBorisVWScale particles.

• By using the overwriteTag in the Species block. When this flag is set to true the species takes reponsi-bility for generating the flags. This is the only option that will work with restore.

If the tags are set manually then the user must insure that the tags are unique or errors will occur tracking the particles.

Example of Using manualSrc to Tag Particles

<Species electrons>kind = relBorisTagged# constants defined previouslycharge = ELECCHARGE mass = ELECMASS# Place a single particle in the macroparticleemField = constMag numPtclsInMacro = 1.## If the manual source is used to create# tagged particles, the tag must be a unique# integer or the particle tracking will not# work.#<ParticleSource SingleParticleSrc>

applyPeriod = 0kind = manualSrc# manual particle loaders always require# AT LEAST 3 velocity components regardless# of NDIM; in this case, NDIM=2p1 = [R_GYRO 0. 0. V_GYRO V_Z 0.]p2 = [0. R_GYRO -V_GYRO 0. V_Z 1.]p3 = [-R_GYRO 0. 0. -V_GYRO V_Z 2.]p4 = [0. -R_GYRO V_GYRO 0. V_Z 3.]

304 Chapter 10. Advanced Concepts

Page 309: VSim In Depth

VSim In Depth, Release 8.2.1

</ParticleSource></Species>

Example of Using tagGen to Tag Particles

<VelocityGenerator velGen>kind = funcVelGen

# This sets the tags to be unique integers so they# can be tracked by the tagged particle tracking# history<STFunc component3>kind = tagGen</STFunc>

</VelocityGenerator>

After you have tagged those particles you would like to track using you can record the particles position and/orvelocities (or other internal variables such as the weight) by using the rm-speciestracktag History.

Example History Block Used to Record Data from Tagged Particles

# Tagged particle trajectory history.<History trajectory>

kind = speciesTrackTag# Any particle with a tag greater than or equal to# the maximum tag will not be tracked.maximumTag = 4xComponents = allspecies = [electrons]

</History>

10.2.4 Controlling the density of physical particles

VSim uses macroparticles to model the kinetics of physical particles. The relationship between the physical densityone wishes to model, and the density of macroparticles used in the simulation, takes the form

𝑛𝑢𝑚𝑃𝑡𝑐𝑙𝑠𝐼𝑛𝑀𝑎𝑐𝑟𝑜 =𝑛𝑜𝑚𝑖𝑛𝑎𝑙𝐷𝑒𝑛𝑠𝑖𝑡𝑦 × 𝑐𝑒𝑙𝑙𝑉 𝑜𝑙𝑢𝑚𝑒

𝑛𝑜𝑚𝑃𝑡𝑐𝑙𝑠𝑃𝑒𝑟𝐶𝑒𝑙𝑙

where

• numPtclsInMacro = number of physical particles in a macroparticle

• nominalDensity = nominal density of physical particles

• cellVolume = volume of a simulation grid cell (or average volume over all cells, if nonuniform)

• nomPtclsPerCell = number of macroparticles in a simulation grid cell

The number of physical particles in a macroparticle can be set directly by including the following in the Species block:

10.2. Advanced Simulation 305

Page 310: VSim In Depth

VSim In Depth, Release 8.2.1

numPtclsInMacro = (float or integer value)

It can also be determined by setting both of the following parameters in the Species block:

nomPtclsPerCell = (float or integer value)nominalDensity = (float value)

The sole purpose of the nominalDensity and nomPtclsPerCell parameters in the top level of a Species block is to calcu-late the number of particles in a macroparticle of that species, according to the relation given above. Alternatively, onecan define this quantity directly using the numPtclsInMacro parameter. With the number of particles in a macroparticlethus determined, one can then load the macroparticles into the simulation domain using one or more ParticleSourceblocks (a sub-block within the Species block); these blocks should be configured to load macroparticles in a mannerconsistent with the desired physical particle density. Many types (kinds) of ParticleSource can be used within VSim;the complete list is given in particlesource.

10.2.5 Use of STFunc blocks to modify density

A number of STFunc input blocks can be used to control or modify the density of physical particles represented bythe simulation. Not all ParticleSource kinds permit the use of such blocks; those that do are listed below. For thesake of clarity, we will divide the ParticleSource kinds which permit the use of such STFunc blocks into two groups:older VSim particle sources (which use a wide variety of methods for density control), and the newer xvLoaderEmitterparticle source, which subsumes many of these older methods under a single interface.

• Older VSim sources

– randdenssrc

– filedenssrc

– planarptclemitter

– gaussdenssrc

– griddensrcvw

• New particle source: the xvLoaderEmitter

– xvloaderemitter

Density modification or control using STFunc blocks is not supported in VSim for ParticleSource kinds which are notlisted above. For the ParticleSource kinds which are listed, the paragraphs below demonstrate various approaches todensity modification using STFunc blocks, both for fixed-weight and variable-weight macroparticles.

Older VSim sources: Fixed-weight macroparticles

Density profiles: loading

When macroparticles are loaded into the simulation using one of the older VSim sources listed above, the physicaldensity profile they generate can be modified by a macroDensFunc. A macroDensFunc is an stfunc (a function allowedto vary in space and time). A typical macroDensFunc STFunc block might look something like this:

<STFunc macroDensFunc>kind = expressionexpression = x/LX

</STFunc>

306 Chapter 10. Advanced Concepts

Page 311: VSim In Depth

VSim In Depth, Release 8.2.1

The macroDensFunc STFunc block appears in the input file as a sub-block of the ParticleSource block. One can useany of the available stfunc-kinds (expression, constantFunc, etc.) within the STFunc block, but “macroDensFunc”must be the name of the block. The output of the function described within this block is bounded by 0 and 1, corre-sponding to the likelihood that we will want to load particles at a given position and time (values > 1 are assumed tobe equal to 1; values < 0 are assumed to be equal to zero). The expression can be any user-specified function of x, y,z, and t, including constants. VSim performs a standard acceptance-rejection algorithm, consistent with this function,to determine if particles will be loaded.

When loading, VSim chooses a particle position {x0,y0,z0} within a cell, picks a random number R between 0 and 1,and evaluates the macroDenFunc STFunc at the current time and the chosen position. If macroDenFunc(x0,y0,z0,t) >R, the particle is loaded; otherwise, the particle is not loaded. Thus, in local volumes where the value of macroDen-Func(x0,y0,z0,t) is small, few particles will be loaded.

The macroDensFunc shown above, when used in a simulation bounded in x in the range [0,LX], will load macroparti-cles preferentially in the domain at higher values of x. The number of macroparticles that will be loaded is about halfthe number that would be loaded if the macroDensFunc block were not included in the simulation, and the physicaldensity which corresponds to these macroparticles is thus reduced.

Density profiles: emitting

When macroparticles are emitted into the simulation using one of the older VSim sources listed above, the physicaldensity of the emitted particles can be modified by a macroFluxFunc. A macroFluxFunc is an stfunc (a functionallowed to vary in space and time). A typical macroFluxFunc STFunc block might look something like this:

<STFunc macroFluxFunc>kind = expressionexpression = y/LY

</STFunc>

The macroFluxFunc appears in the input file as a sub-block of the ParticleSource block. One can use any of theavailable stfunc-kinds (expression, constantFunc, etc.) within the STFunc block, but “macroFluxFunc” must be thename of the block. The output of the function described within this block is bounded by 0 and 1, corresponding tothe likelihood that we will want to emit particles at a given position and time (values > 1 are assumed to be equalto 1; values < 0 are assumed to be equal to zero). The expression can be any user-specified function of x, y, z, andt, including constants. VSim performs a standard acceptance-rejection algorithm, consistent with this function, todetermine if particles will be emitted.

When emitting, VSim chooses a particle position {x0,y0,z0} on the emitting surface, picks a random number Rbetween 0 and 1, and evaluates the macroFluxFunc STFunc at the current time and the chosen position on the emittingsurface. If macroFluxFunc(x0,y0,z0,t) > R, the particle is emitted; otherwise, the particle is not emitted. Thus, onlocal surfaces where the value of macroFluxFunc(x0,y0,z0,t) is small, few particles will be emitted.

The macroFluxFunc shown above, when used in a simulation with an emitting surface in the x-y plane, will emitparticles preferentially from this plane at higher values of y. The number of macroparticles that will be emitted isabout half the number that would be loaded if the macroFluxFunc block were not included in the simulation, and theinflux of physical density which corresponds to these macroparticles is thus reduced.

Older VSim sources: Variable-weight macroparticles

Density profiles: loading

When variable-weight macroparticles are loaded into the simulation using one of the older VSim sources listed above,the physical density profile they generate can be modified using the macroDensFunc STFunc, as described for the caseof fixed-weight macroparticles above. In addition, the particle weights can be modified using the weightFunc STFunc.A typical weightFunc might look something like this:

10.2. Advanced Simulation 307

Page 312: VSim In Depth

VSim In Depth, Release 8.2.1

<STFunc weightFunc>kind = expressionexpression = sqrt((x/LX)^2+(y/LY)^2+(z/LZ)^2)

</STFunc>

One can use any of the available stfunc-kinds (expression, constantFunc, etc.) within this STFunc block, but “weight-Func” must be the name of the block. The weightFunc STFunc block appears as a sub-block of the ParticleSourceblock, and modifies the weights of the loaded macroparticles according to a user-specified function of space and/ortime. The density of physical particles loaded into the simulation can thus be adjusted, since the physical density arisesfrom the weighted macroparticle density.

Density profiles: emitting

When variable-weight macroparticles are emitted into the simulation using one of the older VSim sources listed above,the physical density profile of the emitted particles can be modified using the macroFluxFunc STFunc, as describedfor the case of fixed-weight macroparticles above. In addition, the macroparticle weights can also be modified usingthe weightFunc STFunc, as described for the case of loading variable-weight macroparticles above.

The weightFunc STFunc block appears as a sub-block of the ParticleSource block, and modifies the weights of theemitted macroparticles according to a user-specified function of space and/or time. (The weightFunc specified by theuser must properly take into account the geometry of the surface from which particles are emitted.) The density ofphysical particles emitted into the simulation can thus be adjusted, since the physical density arises from the weightedmacroparticle density.

In simulations which use the planarPtclEmitter ParticleSource, additional options for modifying the macroparticleweights are enabled by the currentDensityFunc STFunc and/or the fluxDensityFunc STFunc. These STFunc blocksallow users to specify a known current density or flux density to model the particle emission.

For the currentDensityFunc, the STFunc block takes the form

<STFunc currentDensityFunc>kind = expressionexpression = <analytic function of x, y, z, t>

</STFunc>

(though it may use another of the stfunc-kinds) and the ensuing macroparticle weights are computed from the relation

𝑤𝑒𝑖𝑔ℎ𝑡 =𝑐𝑢𝑟𝑟𝑒𝑛𝑡𝐷𝑒𝑛𝑠𝑖𝑡𝑦𝐹𝑢𝑛𝑐× 𝑡𝑜𝑡𝑎𝑙𝐴𝑟𝑒𝑎× 𝑑𝑡

𝑚𝑎𝑐𝑟𝑜𝐶ℎ𝑎𝑟𝑔𝑒× 𝑛𝑢𝑚𝑀𝑎𝑐𝑟𝑜𝑃𝑡𝑐𝑙𝑠

wherein

• currentDensityFunc is the value of its STFunc at the macroparticle position and time,

• totalArea is the surface area of the emitting surface,

• dt is the timestep,

• macroCharge is the charge of the macroparticle,

• numMacroPtcls is the number of macroparticles emitted per timestep.

For the fluxDensityFunc, the STFunc block takes the form

<STFunc fluxDensityFunc>kind = expression

308 Chapter 10. Advanced Concepts

Page 313: VSim In Depth

VSim In Depth, Release 8.2.1

expression = <analytic function of x, y, z, t></STFunc>

(though it may use another of the stfunc-kinds) and the ensuing macroparticle weights are computed from the relation

𝑤𝑒𝑖𝑔ℎ𝑡 =𝑓𝑙𝑢𝑥𝐷𝑒𝑛𝑠𝑖𝑡𝑦𝐹𝑢𝑛𝑐× 𝑡𝑜𝑡𝑎𝑙𝐴𝑟𝑒𝑎× 𝑑𝑡

𝑚𝑎𝑐𝑟𝑜𝐶ℎ𝑎𝑟𝑔𝑒× 𝑛𝑢𝑚𝑀𝑎𝑐𝑟𝑜𝑃𝑡𝑐𝑙𝑠

wherein

• fluxDensityFunc is the value of its STFunc at the macroparticle position and time,

• totalArea is the surface area of the emitting surface,

• dt is the timestep,

• macroCharge is the charge of the macroparticle,

• numMacroPtcls is the number of macroparticles emitted per timestep.

In simulations which use the planarPtclEmitter ParticleSource, and which specify more than one method for modifyingthe macroparticle weights, the STFunc blocks are applied in the following order of precedence: currentDensityFunc,fluxDensityFunc, and finally weightFunc.

xvLoaderEmitter: Fixed-weight macroparticles

Density profiles: loading

When fixed-weight macroparticles are loaded into the simulation using the xvLoaderEmitter source, the physicaldensity profile they generate can be modified using the relMacroDenFunc STFunc. A typical relMacroDenFunc stfuncmight look something like this:

<STFunc relMacroDenFunc>kind = expressionexpression = 4.0*x/LX*(1-x/LX)

</STFunc>

It appears in the Species block at the same level as the particle PositionGenerator and VelocityGenerator blocks. Onecan use any of the available stfunc-kinds (expression, constantFunc, etc.) within the STFunc block, but “relMacroDen-Func” must be the name of the block. The output of the function described within this block is bounded by 0 and 1,corresponding to the likelihood that we will want to load particles at a given position and time (values > 1 are assumedto be equal to 1; values < 0 are assumed to be equal to zero). The expression can be any user-specified function ofx, y, z, and t. VSim performs a standard acceptance-rejection algorithm, consistent with this function, to determine ifparticles will be loaded.

When loading, VSim chooses a particle position {x0,y0,z0} within a cell, picks a random number R between 0and 1, and evaluates the relMacroDenFunc STFunc at the current time and the chosen position. If relMacroDen-Func(x0,y0,z0,t) > R, the particle is loaded; otherwise, the particle is not loaded. Thus, in local volumes where thevalue of relMacroDenFunc(x0,y0,z0,t) is small, few particles will be loaded.

Note that VSim’s attempt to load the user-specified number of particles per cell will occur prior to the application ofthe relMacroDenFunc acceptance-rejection algorithm. This means that a 100-cell simulation with 10 particles per cellwill not necessarily be initialized with 1000 particles – instead, it will be initialized with whatever fraction of 1000particles is consistent with the user-specified relMacroDensFunc. (If, for instance, relMacroDenFunc were set to 0.25,VSim would attempt to load 1000 particles in the domain, but relMacroDenFunc would probabilistically permit onlyabout 250 of these particles to actually be loaded.)

10.2. Advanced Simulation 309

Page 314: VSim In Depth

VSim In Depth, Release 8.2.1

Density profiles: emitting

When fixed-weight macroparticles are emitted into the simulation using the xvLoaderEmitter source, the physicaldensity profile they generate can be modified using the relMacroFluxFunc STFunc. A typical relMacroFluxFuncstfunc might look something like this:

<STFunc relMacroFluxFunc>kind = expressionexpression = z/LZ

</STFunc>

It appears in the Species block at the same level as the particle PositionGenerator and VelocityGenerator blocks.One can use any of the available STFunc kinds (expression, constantFunc, etc.) within the STFunc block, but “rel-MacroFluxFunc” must be the name of the block. The output of the function described within this block is boundedby 0 and 1, corresponding to the likelihood that we will want to emit particles at a given position and time (values >1 are assumed to be equal to 1; values < 0 are assumed to be equal to zero). The expression can be any user-specifiedfunction of x, y, z, and t. VSim performs a standard acceptance-rejection algorithm, consistent with this function, todetermine if particles will be emitted.

When emitting, VSim chooses a particle position {x0,y0,z0} on the emitting surface, picks a random number Rbetween 0 and 1, and evaluates the relMacroFluxFunc STFunc at the current time and the chosen position. If rel-MacroFluxFunc(x0,y0,z0,t) > R, the particle is emitted; otherwise, the particle is not emitted. Thus, on local surfaceswhere the value of relMacroFluxFunc(x0,y0,z0,t) is small, few particles will be emitted.

Note that VSim’s attempt to emit the user-specified number of particles will occur prior to the application of therelMacroFluxFunc acceptance-rejection algorithm. This means that a simulation configured to emit 100 macroparticlesper timestep, in the absence of relMacroFluxFunc, will not necessarily emit this many macroparticles per timestep -instead, the number of macroparticles emitted will some fraction of 100-per-timestep that is consistent with the user-specified relMacroFluxFunc. (If, for instance, relMacroFluxFunc were set to 0.4, VSim would attempt to emit 100particles per timestep, but relMacroFluxFunc would probabilistically permit only about 40 of these particles to actuallybe emitted.)

xvLoaderEmitter: Variable-weight macroparticles

Density profiles: loading

When variable-weight macroparticles are loaded into the simulation using the xvLoaderEmitter source, the physicaldensity profile they generate can be modified using the relMacroDenFunc STFunc. This function behaves the same as itdoes for fixed-weight macroparticles, as described above. In addition, the macroparticle weights can be modified usingthe velocity-generator-details block. To use this block, one needs to know the number of internal variables associatedwith the chosen Species block (which contains the ParticleSource block which will contain the VelocityGeneratorblock). Each macroparticle has a number of internal variables - some number of velocity components (usually 3), apossibly varying weight (1), a tag (1), etc. The particle weight is the last internal variable, and the internal variablecount begins at zero. Thus, an untagged variable-weight species in Cartesian geometry with three velocity componentshas the structure

• component0 : x velocity

• component1 : y velocity

• component2 : z velocity

• component3 : macroparticle weight

while a tagged variable-weight species in Cartesian geometry with three velocity components has the structure

• component0 : x velocity

310 Chapter 10. Advanced Concepts

Page 315: VSim In Depth

VSim In Depth, Release 8.2.1

• component1 : y velocity

• component2 : z velocity

• component3 : macroparticle tag

• component4 : macroparticle weight

The exact structure of these lists will depend on the dimensionality of the problem setup and the Species kind.

The weights of the loaded particles can thus be modified by defining a suitable VelocityGenerator of the form

<VelocityGenerator componentN>(one of the allowable VelocityGenerator kinds)

</VelocityGenerator>

where N, in the “componentN” block name, is an integer corresponding to the index of the weight-component in thelist of internal macroparticle variables. Any of the VelocityGenerator kinds (see velocity-generator-details) may beused.

Density profiles: emitting

When variable-weight macroparticles are emitted into the simulation using the xvLoaderEmitter source, the physicaldensity profile they generate can be modified using the relMacroFluxFunc STFunc. This function behaves the sameas it does for fixed-weight macroparticles, as described above. In addition, the macroparticle weights can be modifiedusing a currentDensityFunc STFunc block, which enables the user to specify a known current density to model theemission.

For the currentDensityFunc, the STFunc block takes the form

<STFunc currentDensityFunc>kind = expressionexpression = <analytic function of x, y, z, t>

</STFunc>

(though it may use another of the stfunc-kinds, the STFunc block must be named “currentDensityFunc”). This STFuncblock appears as a sub-block within the ParticleSource block. The ensuing macroparticle weights are computed fromthe relation

𝑤𝑒𝑖𝑔ℎ𝑡 =𝑐𝑢𝑟𝑟𝑒𝑛𝑡𝐷𝑒𝑛𝑠𝑖𝑡𝑦𝐹𝑢𝑛𝑐× 𝑒𝑚𝑖𝑠𝑠𝑖𝑜𝑛𝐴𝑟𝑒𝑎× 𝑑𝑡

𝑚𝑎𝑐𝑟𝑜𝐶ℎ𝑎𝑟𝑔𝑒× 𝑛𝑢𝑚𝑀𝑎𝑐𝑟𝑜𝑃𝑡𝑐𝑙𝑠𝑃𝑒𝑟𝑆𝑡𝑒𝑝

wherein

• currentDensityFunc is the value of its STFunc at the macroparticle position and time,

• emissionArea is the surface area of the emitting surface,

• dt is the timestep,

• macroCharge is the charge of the macroparticle,

• numMacroPtclsPerStep is the number of macroparticles emitted per timestep.

10.2.6 Dey-Mittra Conformal Boundary Algorithm

Explanation of how Vorpal resolves non-rectilinear grid boundaries.

10.2. Advanced Simulation 311

Page 316: VSim In Depth

VSim In Depth, Release 8.2.1

Dey-Mittra Algorithm

To lowest order, a boundary for a curved PEC (perfect electric conductor) can be represented on a Cartesian mesh asshown in Figure 10.3. Also known as stair-stepping, the boundary is approximated by completely filling-in with PECmaterial any cell whose centroid lies within the surface. The grey cells in the figure demonstrate the sort of surfacethat would result.

Fig. 10.3: Lowest-order rendering of a grid boundary. The blue line is the real boundary and the grey shading indicateswhere boundary material actually winds up.

Including or excluding cells is an order-unity error at the boundary, which results in a first-order error in globalquantities, like mode frequencies, scattering, mode shape away from the boundary, etc. Because the results error isfirst order, it decreases only very slowly with the number of cells. E.g., to reduce the error to one percent, one wouldhave to have a cell length no greater than 𝜆

100 , resulting in a requirement of a million cells in 3D.

Vorpal stores boundaries as a sequence of conformal linear approximations, as in Figure 10.4. This means that eachcell that falls along the boundary is cut in two: a straight line is drawn between the points where the boundary intersectsthe coordinate grid, and PEC material is filled-in only on the outside of the boundary. The interior simulation spacesufficiently resembles the true shape to preserve 2nd order accuracy.

There is a cost to doing this: dividing a Yee-cell involves several algorithmic complications. Because Vorpal employsthe Dey-Mittra technique for conformal boundaries, only the Faraday loop need be modified (Figure 10.5): the electricfield vector along the cut edge and the magnetic field vector must be interpolated from the surrounding points. Thesecalculations impose limitations on the maximum time-step, see the discussion of dmFrac below.

dmFrac Explained

The CFL number is dependent on the size of the smallest cell. When cells are significantly smaller around the edges,the maximum stable time-step must necessarily shrink in direct proportion. In the case of highly unequal divisions-—take for example, cell 46 in Figure 10.4, the lower left corner of which must be treated as its own, minisculecell—-the new CFL number may constrain the time-step to an infinitesimal length, breaking the simulation. To dealwith this, Vorpal uses the Dey-Mittra conformal scheme, a computational technique that finds a best compromisebetween the conventional 1st order method and the fully conformal 2nd order method.

In brief, Vorpal tries to apply a conformal boundary everywhere along the edge of a surface. Any place where thisresults in a time-step that is “too small” Vorpal skips over by stair-stepping at that location. The PEC boundary ofFigures 10.3 and 10.4 is rendered in this way in Figure 10.6.

312 Chapter 10. Advanced Concepts

Page 317: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 10.4: Conformal rendering of the grid boundary that maintains 2nd-order accuracy. The black dashed lines rep-resent the sequence of linear approximations, conjoined on the grid lattice, that Vorpal uses to construct the boundaryline.

Fig. 10.5: Execution of the Dey-Mittra technique requires interpolation of the E-field and B-field vectors to new gridlocations on the cut cells.

10.2. Advanced Simulation 313

Page 318: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 10.6: The same boundary rendered using the CFL_FACTOR test quantity.

In greater depth, the quantity dmFrac is defined in the pre file and establishes the smallest fraction of the conventionaltime-step that we are willing to tolerate. This means the time-step will be (unless the user overrides it):

Timestep = dmFrac × TIMESTEP_FACTOR × ∆𝑡𝐶𝐹𝐿.

For a dmFrac of 0.25, the time step will be reduced by a factor of 4 and the simulation will take 4 times longer to run.

As an example we look at a coaxial cable simulation. Setting dmFrac to 0.05 allows the fields to conform well alongthe outer wall of the coax. With this value of dmFrac there are 248 cells in which the fields have been set to zero dueto their timestep becoming too small.

Fig. 10.7: Coax fields with dmFrac=0.05

If we run the same simulation but with a dmFrac value of 0.95 the number of excluded cells jumps up to 16772.Clearly the fields do not conform as well with outer coax wall:

314 Chapter 10. Advanced Concepts

Page 319: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 10.8: Coax fields with dmFrac=0.95

Recommendations for dmFrac

Quick summary:

dmFrac Accuracy Speed0 Second Order Slow1 First Order Fast

Finding the optimal dmFrac is important. Typically EM simulation packages have hard coded analogous dmFracvalues:

PBA → dmFrac = 0.25

FastPBA → dmFrac = 0.8

VSim allows complete felxibility of the dmFrac in that it is a user defined variable. However, experience has fleshedout some recomendations:

For pure EM problems:

• For routine running setting dmFrac = 0.7 provides a good balance between speed and accuracy.

• Setting dmFrac = 0.1 allows you to check if your answer has converged.

• When performing many runs on similar geometry do a quick scan of possible dmFrac values to find theoptimal one.

For EM particle problems:

• For routine running setting dmFrac = 0.3 provides a good balance between speed and accuracy.

• Setting dmFrac = 0.5 allows you to check if your answer has converged.

• When performing many runs on similar geometry do a quick scan of possible dmFrac values to find theoptimal one.

Ultimately dmFrac directly affects the simulation timestep and indirectly affects the simulated geometry. In manycases even with dmFrac =1 there will still be cells that are cut because the timestep there becomes too small.

10.2. Advanced Simulation 315

Page 320: VSim In Depth

VSim In Depth, Release 8.2.1

Further Reading

10.2.7 Introduction to Far Fields in VSim

Overview: Using Far Fields

VSim can easily perform near-field-to-far-field transformations on most fields. This is executed through the use ofseveral macros and a post simulation analysis script. These are:

• Far Fields Macro File

• Add Far Field History Macro

• rm-kirchhoff

• computeFarFieldRadiation.py – Far Field Analysis

Fig. 10.9: “Rosa Floribunda VSim.” Far field pattern for a parabolic dish transmitter.

To add far fields to a simulation,

1. Make a call to the addFarFields() macro (see Far Fields Macro File).

2. Make a call to the addFarFieldsHistory() macro (see Add Far Field History Macro).

Here is a snippet of code that does this:

<XSim RCSSphere>shortDescription = "Radar Cross Section of a Sphere"description = "Radar Cross Section of a Perfectly Conducting Sphere"longDescription = "A radar cross section is computed of a perfectly

→˓conducting sphere."canChangeDt = truecanChangeNdim = falseanalyzers = [computeFarFieldRadiation.py]

</XSim>

$ import farFields.mac$ import antennas.mac

316 Chapter 10. Advanced Concepts

Page 321: VSim In Depth

VSim In Depth, Release 8.2.1

# == Add Far Fields to Compute RCS ==addFarFields()

# Create RCS history$ NUM_THETA = 45$ NUM_PHI = 90$ NS = 60$ BOXHALFLENGTH_METERS = WAVELENGTH$ RS = sqrt(3*BOXHALFLENGTH_METERS**2) + 5.*DX$ HISTORY_DELAY = (LX/2)/(LIGHTSPEED)addFarFieldHistory(farField,NUM_THETA,NUM_PHI,RS,NS,HISTORY_DELAY,FREQUENCY)

The far field radiation pattern is always calculated in spherical coordinates, regardless of what coordinate system therest of the simulation uses. Thus, you must specify a grid resolution for the sphere, and this is where the parametersNUM_THETA and NUM_PHI come from. Generally 45 and 90 respectively are good choices.

The simulation must run long enough for the Kirchhoff Integral to reach the flat top value–more on that below. After therun has completed, proceed to the Analyze window and select computeFarFieldRadiation.py from the list of analysisscripts. This will appear in the list of active analyzers if you included it in the <xsim> block of your input file, as inthe example above (<xsim> block is optional). If it is not present in the list, you will have to browse for it manually.

Fig. 10.10: Analysis Window with the computeFarFieldRadiation.py script loaded up.

• simulationName will be the base name of your input file. The analysis script will use this to find the _History.h5file in the run directory.

• historyName is whatever name you gave the far field history when you called addFarFieldHistory. Within the_History.h5 file there are multiple datasets and this points the analysis script to the right one.

• NUM_PHI and NUM_THETA must be the same as whatever value you gave them in the input file. If you givethem different values here the far field pattern will come out spikey and discontinuous as in Fig. 10.11.

10.2. Advanced Simulation 317

Page 322: VSim In Depth

VSim In Depth, Release 8.2.1

• SLL–short for Side Lobe Level, this specifies the smallest acceptable magnitude. For example, an SLL of 40will display every data point greater than or equal to -40dB and adjust any smaller values upward to -40dB. SLLalso controls the plotting radius of the field: an SLL of 40 will plot smaller than would the same field with anSLL of 20.

• normalize, if enabled, the data output will be rescaled between a maximum of 0 and a minimum of -SLL.

Fig. 10.11: A bad far field. The discontinuous appearance is the result of specifying values of NUM_PHI andNUM_THETA during analysis that are inconsistent with the far field history.

To visualize the far field, go to the Visualize window and select it under Scalar Data. There will also be a mesh underMeshes.

Understanding Far Fields

A far field transformation is a computational short cut that lets us compute the radiation pattern in the far field regionwithout having a domain that is 10’s of meters long, and without having to run the simulation for the long time scalesnecessary for light to propagate to those distant points. Imagine an observation point 10m from the source. At anyinstant in time the light reaching that point from the near fields will have been delayed by the time it took for thephotons to traverse the separation distance. Light from the near end of the source will take a shorter time to reach theobservation point than will light from the far end. Hence, an observer at the far point will see the two opposite ends ofthe near field at two different instants in time. The problem of simultaneity can be resolved a priori by performing thetransformation on each near field region at the time when the far field observer will perceive it.

The method hinges on the Kirchhoff surface integral which extrapolates what the near field pattern will look likeat some far field distance DFF and some far field time TFF. (If we want to predict what earth will look like to analien astronomer, we need to know: where are they?–DFF, and when are they?–TFF.) The Kirchhoff integral is a lineintegral performed over an imaginary surface, called the Kirchhoff surface, which encloses the simulation geometry.Refer to Fig. 10.12. VSim currently uses only a Kirchhoff sphere, though other surface shapes are possible and maybe included in the future. The surface integration is discretized into a summation of line integrals:

318 Chapter 10. Advanced Concepts

Page 323: VSim In Depth

VSim In Depth, Release 8.2.1

Let,

• 𝑡′ = 𝑡𝑠𝑖𝑚 = simulation time (i.e. Timestep*DT)

• 𝑡𝐹𝐹 = far field time, a positive constant number measured with respect to 𝑡′ = 0

• 𝑅𝑆 = radius of the Kirchhoff sphere‘

• 𝐷𝐹𝐹 = distance from far point to Kirchhoff sphere centroid

• 𝑥𝐹𝐹 = distance along 𝐷𝐹𝐹 measured from far point

• 𝑥′ = distance along 𝐷𝐹𝐹 measured from Kirchhoff sphere centroid to 𝑥𝐹𝐹

See Fig. 10.13 for a pictorial explanation of these quantities. This implies that 𝐷𝐹𝐹 = 𝑥𝐹𝐹 − 𝑥′. The KirchhoffIntegral then takes the form, ∫ ∞

0

𝐸 (𝑥𝐹𝐹 , 𝑡𝐹𝐹 , 𝑥′, 𝑡′) 𝑑𝑡′ (10.2)

where 𝐸 (𝑥𝐹𝐹 , 𝑡𝐹𝐹 , 𝑥′, 𝑡′) may be written parametrically:

𝑡′ +𝑥𝐹𝐹

𝑐

= 𝑡′ +

𝐷𝐹𝐹 + 𝑥′

𝑐

= 𝑡𝐹𝐹 . (10.3)

The absolute value yields a family of solutions which defines a small-circle-of-a-sphere (small in the geometric sense,i.e. not a great-circle). This small-circle is identical to the circle of intersection formed by the Kirchhoff sphere and thesphere of observation centered on the far point. The “sphere of observation” here is the field of information availableright now at 𝑡𝑠𝑖𝑚 that will reach the far point at time TFF. Intuitively, it has radius of 𝑐 (𝑡𝐹𝐹 − 𝑡′) as shown in Fig.10.13.

Fig. 10.12: Process by which a near-to-far field transformation is accomplished for an observation point that has space-time separation 𝐷𝐹𝐹 , 𝑡𝐹𝐹 from the scattering object (scattering object is the green shape). By default 𝐷𝐹𝐹 = 10m inaddFarFieldHistory(), but it can be customized in the addFarFieldHistoryPowerUser() macro.

10.2. Advanced Simulation 319

Page 324: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 10.13: Upper right: The intersection of the Kirchhoff sphere and the sphere of observation makes a circle ofintersection that defines the path of integration.Lower half: Definition of 𝑥𝐹𝐹 and 𝑥′. The cutaway highlights the circle of intersection. Along the vector joining the centroids ofeither sphere: 𝑥′ is the distance from the Kirchhoff sphere centroid to the circle of intersection; 𝑥𝐹𝐹 is the distance from the far

point to the circle of intersection.

320 Chapter 10. Advanced Concepts

Page 325: VSim In Depth

VSim In Depth, Release 8.2.1

The far field time is a constant interval and is chosen by the user, albeit indirectly; usually there is some ramp-up timeat the beginning of the simulation for near-fields to become well established around the Kirchhoff sphere. We don’twant to begin the far field calculation until the near fields are in place. Thus, we specify the simulation time at whichthe far field transformation should begin. This is the HIST_DELAY argument that gets passed to addFarFieldHistory(),and the macro works backwards to determine 𝑡𝐹𝐹 using the begin condition given in Fig. 10.12.

For every time step, all points satisfying Equation (2) are integrated over with a closed line integral:∮ 𝑁𝑆

0𝐸 (𝑥′) 𝑑𝑥′.

The results are stored in the history file. The history is a running sum, that is, each time step corresponds to a row inthe history file and each row is the sum of the current Kirchhoff integral result plus the previous row. These steps arerepeated for every time step regardless of beginning and ending conditions, however, only those simulation times forwhich a solution to Equation (2) exists will yield a non-zero result. Until that equation can be solved by some familyof points on the Kirchhoff sphere, the Kirchhoff Integral evaluates to zero. Referring once again to Fig. 10.13, theinitial sphere of observation will have radius 𝑐 (𝑡𝐹𝐹 ) and this will lie somewhere out in space beyond the Kirchhoffsphere (if it doesn’t, you’ve done something wrong!). As the simulation time increments, the sphere of observationshrinks toward its origin at the far point according to 𝑐 (𝑡𝐹𝐹 − 𝑡′) and comes to pass through the Kirchhoff sphere. Asthe sphere of observation sweeps through the Kirchhoff sphere, the path of integration advances every time step andintegrates around the circle of intersection. The result is added to the running sum and the time step advances. Aftera time 2𝑅𝑆

𝑐 , the sphere of observation will shrink toward the far field point beyond the radius of the Kirchhoff sphere,and the integration will once again evaluate to zero. This is the flat-top period and it indicates that the Kirchhoffsurface integral is complete. For most examples involving far fields, this will be as long as they need be run. ThecomputeFarFieldRadiation.py analysis script uses only the last row in the History file.

The discussion heretofore has outlined the transformation procedure for a single point in the far field. The far fieldis comprised of many such far points, the total number of which depends on the NUM_PHI and NUM_THETAresolutions specified by the user: NUM_PHI*NUM_THETA = Total number of far points.

One final caveat has to do with the way amplitudes are obtained. The Kirchhoff integral will only pick up whateverfield values happen to be crossing the Kirchhoff sphere at the time of integration. In order to obtain the full scaleamplitude of the wave the far field history actually takes 17 different integrals at every time step. The 17 differentintegrals correspond to 17 different far field times 𝑡𝐹𝐹 spanning one period of the test frequency. In the post runanalysis these 17 points will be beaten with a sine wave and cosine wave so that the amplitude can be extracted fromthe Fourier coefficients.

Incrementing 𝑡𝐹𝐹 re-expands the sphere of observation by some small amount and this constitutes a shift of the lineintegral backward on the Kirchhoff sphere by a distance +𝛿𝑥′. Thus, at each time step the far field history performsone line integral at 𝑥′ and then at 16 decrements of 𝑥′ + 𝛿𝑥′. Upon arrival of the next time step the whole sequenceis picked up and moved and the process is repeated. This means that 𝑥′ is really the leading edge of an envelope ofintegration that passes through space and over the Kirchhoff sphere. In this way, the far field observation is not locatedat any one instant in time, TFF, but over a far field time interval: TFFMIN to TFFMAX. The values of TFFMIN,TFFMAX, and the interval divisor NTFAR may be directly set through the Add Far Field History Power User Macro.NTFAR is 16 by default. If you wish to increase this resolution be aware that the history file can become quite largebecause it contains a number of data points equal to NUM_PHI*NUM_THETA*(NTFAR+1)*NSTEPS.

10.2.8 Monte Carlo Interactions Package

Monte Carlo Interactions package: allows the user to model random interactions that involve differentobjects in the simulation, such as Species, Fluids, and Fields. In a simulation, macroparticles of one speciesmay interact with macroparticles of another species, such as in a collision like impact ionization. Alternately,macroparticles of a species can interact with a Fluid or a Field. There are some random interactions that involveonly fluids and fields, such as field ionization of a neutral gas, where a fluid represents the neutral gas.

There are two kinds of objects used by the Monte Carlo Interactions package: the incidentSelector object and theinteraction objects themselves. To help remain clear as we describe these objects, we will define some terminologythat will be used in this chapter:

10.2. Advanced Simulation 321

Page 326: VSim In Depth

VSim In Depth, Release 8.2.1

• interaction: The italicized word interaction is used to describe the specific kind of interaction used in asimulation, such as impact ionization with an impacting species colliding with a neutral fluid backgroundgas.

• incident: The italicized word incident is used to describe a particular example of an interaction event. Inthe impact ionization macroparticle N of the impacting species colliding with the neutral fluid in cell(i,j,k) in which macroparticle N is located. There are two general kinds of incidents in a given simulation:possible incidents and selected incidents. Possible incidents are incidents that can potentially occur, basedon the interaction algorithm and a probability for occurring. Selected incidents are incidents that have beenselected to be performed, a subset of the list of possible incidents.

• incidentSelector: The incident selector is an object in Vorpal that determines the selected incidents fromthe list of possible incidents. There are various algorithms for doing this, with each method best suitedfor different simulation situations. For any given list of interactions in a simulation, there can be only oneincidentSelector. By separating the interactions and the incidentSelector, we can distinguish between theinteraction physics and the Monte Carlo algorithm.

The next sections describe how the Monte Carlo Interaction package works in general and how to use it in VSimsimulations.

Resolution Issues with Monte Carlo Interactions

Like all simulation, resolution is very important for accurate modeling of the desired physics. For Monte Carlointeractions, resolution issues can be slightly different than for other simulations. Like the simulation of other manyother processes, it is important to resolve the physical distributions of the interacting particles as well as the temporalevolution of the distributions. However, for Monte Carlo interactions, additional demands must be satisfied to properlyresolve the physics.

First, consider the issue of spatially resolving the interaction physics. The most obvious aspect of this issue is makingsure that the number of macroparticles in the simulation is large enough to smoothly resolve the spatial distributions ofthe species. Additionally, however, random interactions between particles occur with non-negligible probability onlywhen the particles are in close proximity. To avoid checking the

𝑁2

distances between

𝑁

interacting macroparticles, the VSim Monte Carlo Interactions package limits interactions to those between macropar-ticles within the same cell. This reduces the number of possible interactions to

𝑁cells(𝑁ppc)2

where

𝑁cells

is the number of cells in the simulation and

𝑁ppc

is the number of particles per cell. Hence,

𝑁 = 𝑁ppc𝑁cells

and

𝑁2 = (𝑁cells)2(𝑁ppc)

2 ≫ 𝑁cells(𝑁ppc)2

Spatial resolution of the interactions, then, requires using a grid that properly resolves physical distributions of theparticles as well.

322 Chapter 10. Advanced Concepts

Page 327: VSim In Depth

VSim In Depth, Release 8.2.1

Temporal resolution is also of crucial importance for accurate modeling of the interactions. Temporal evolution of theparticles distributions is obviously part of this, but temporal resolution in random interactions involves more than justthe physical motion of the particles themselves. Each Monte Carlo interaction has an intrinsic time scale set by thephysics of the interaction itself. In other words, the probability for an interaction event to occur can be written as

𝑃 = 𝑑𝑡/𝑇𝑖

where

𝑑𝑡

is the simulation time step and

𝑇𝑖

is the natural time scale associated with the interaction itself. The fundamental probability for an interaction event tooccur between two macroparticles in a given cell with volume V, in a time-step

𝑑𝑡

is

𝑃 = 𝑁1𝑁2𝜎(𝑣)𝑣𝑑𝑡/(𝑁𝑥𝑉 )

where 𝑣 is the relative velocity between the two macroparticles,

𝑁1

and

𝑁2

are the numbers of physical particles per macroparticle for each colliding species, and

𝑁𝑥

is the number of physical particles per macroparticle in the final-state species. This implies that the natural time scaleassociated with this numerical process is:

𝑇𝑖 = 𝑁𝑥𝑉/(𝑁1𝑁2𝜎(𝑣)𝑣).

If the simulation time step

𝑑𝑡

is not small enough to resolve the natural interaction time scale, then inaccurate statistics will result. As one can seefrom the form of the fundamental time scale, however, it is possible to tune the natural time scale for an interaction bychanging the number of fundamental particles per macroparticle in the involved species. However, it should be notedby the user that if a species participates in multiple interactions, it could be challenging to properly resolve all of thedifferent natural time scales in a single simulation.

The last issue of resolution comes from the need to accurately sample the velocity distributions of the interactingparticles. Since the probability for an interaction event to occur non-trivially depends on the particle velocities, andsince a single macroparticle samples only one point in velocity space, accurate statistics may only be achieved in somesimulations with many macroparticles per cell, such that the velocity distributions of the participating species are wellsampled within each cell.

Together, these three issues of resolution can lead to very demanding conditions. It is not uncommon for the spatialand velocity resolution demands to lead to large numbers of cells in the simulation as well as large numbers ofmacroparticles per cell. Temporal resolution demands can lead to very small time steps and very long simulations.The user should address all of these issues when the simulation is being designed.

10.2. Advanced Simulation 323

Page 328: VSim In Depth

VSim In Depth, Release 8.2.1

Monte Carlo Interactions in Vorpal

The Monte Carlo Interactions package is used in simulations via the MonteCarloInteractions block. Inside the Mon-teCarloInteractions block, the user must specify the kind of incidentSelector to use with the selector attribute. Then,within the MonteCarloInteractions block, the user must sequentially add all of the individual Interaction blocks foreach interaction to be simulated. Details on each interaction can be found in VSim Reference.

Example MonteCarloInteraction Block Used to Simulate Field Ionization

In this example CsNeutralGas is the name of a neutral gas fluid block, electrons is the name of the speciesrepresenting the electrons, Cs1 is the name of the species representing the ionized gas.

<MonteCarloInteractions myMC>

<IncidentSelector myselector>kind = nullOnlySelector

</IncidentSelector>

<NullInteraction FluidIonizationCs>kind = nullFieldIonizationinput = CsNeutralGaselectrons = electronsions = Cs1polarizationFlag = 1frequency = 1.e15

</NullInteraction></MonteCarloInteractions>

10.2.9 External Circuit Model

General Theory

The external circuit module in Vorpal follows the method of V. Vahedi and G. DiPeso1. In Vorpal this method is ex-tended to three-dimensional electromagnetic and electrostatic solvers, in additional to two-dimensional electrostatics.In principle, the total current, 𝐽𝑡 = 𝜕𝐷

𝜕𝑡 + 𝐽 , is conserved through the whole system. In the external circuit, the totalcurrent 𝐽𝑡 is solved from the different equation based on its impedance (resistance R, inductance L, capacitance C) andsource components of the circuit. In the simulated plasma region, the total current consists of displacement current 𝜕𝐷

𝜕𝑡and convective current carried by charged particles 𝐽 . Matching these two at the boundary provides a time-dependentboundary condition for the simulated plasma region.

Considering a device that is connected to an external circuit via two electrodes, such as a electron gun or plasmadischarging chamber, the total electric field between the electrodes is decomposed due to linear superposition as��𝑡𝑜𝑡(𝑡) = ��(𝑡) + 𝜑(𝑡)��0, where ��𝑡𝑜𝑡(𝑡) is the total electric field at time t that is used to advance charged particledynamics. Electric field ��(𝑡) is obtained by solving the Maxwell‘s equations for electric (��) and magnetic (��) fields,assuming perfect electric conducting boundary conditions on the two electrodes that are both grounded. 𝜑(𝑡) is thetime-dependent potential difference between the anode and the cathode that can be measured via pseudopotential. Theelectric field ��0 is a constant field that is solved with 1 volt potential difference between the electrodes and no chargedparticles or currents between them. ��0 is essentially a vacuum field with unit potential.

The potential 𝜑(𝑡) is related to the total charge 𝑄(𝑡) on one electrode as 𝑄(𝑡) = 𝐶0𝜑(𝑡). As there is a fix capacitance𝐶0 for the device when vacuum is assumed, its potential is proportional to the total charge. The charge under 1

1

22. Vahedi and G. DiPeso, Journal of Computational Physics 131, 149-163 (1997).

324 Chapter 10. Advanced Concepts

Page 329: VSim In Depth

VSim In Depth, Release 8.2.1

volt potential is 𝑄0, thus at any time t, the electrode potential is 𝜑(𝑡) = 𝑄(𝑡)/𝑄0. The total field is written as��𝑡𝑜𝑡(𝑡) = ��(𝑡) + 𝑄(𝑡)

𝑄0��0, where 𝑄(𝑡) is calculated at each time step via equations of external circuit, and 𝑄0 can be

obtained after solving ��0.

For a general series RCL circuit as shown in figure Sketch of a plasma simulation with a general RLC external circuit.,applying Kirchhoff’s law to the electrode yields the current equation, 𝑑𝑄

𝑑𝑡 = 𝐼𝑐𝑜𝑛𝑣 + 𝐼 , where 𝐼 is the current in theexternal circuit that depends on its source and impedance. 𝐼𝑐𝑜𝑛𝑣 is the plasma convection current at the electrode,representing charges emitted or absorbed by the electrode at each time step.

Fig. 10.14: Sketch of a plasma simulation with a general RLC external circuit.

The voltage equation is obtained by applying Kirchhoff’s law around the circuit, 𝐿𝑑2𝑄𝑐

𝑑𝑡2 +𝑅 𝑑𝑄𝑐

𝑑𝑡 + 𝑄𝑐

𝐶 = 𝑉 (𝑡)−𝜑(𝑡)where 𝑄𝑐 is the charge in the external circuit capacitor. It is related to the external circuit current via 𝐼 = 𝑑𝑄𝑐/𝑑𝑡.Substituting this relation into current equation yields 𝑑𝑄

𝑑𝑡 = 𝐼𝑐𝑜𝑛𝑣 + 𝑑𝑄𝑐

𝑑𝑡 . In PIC simulations, the convective current𝐼𝑐𝑜𝑛𝑣 and the potential difference between two electrodes are defined as 𝐼𝑐𝑜𝑛𝑣 = 𝐼𝑒𝑚𝑖𝑡𝑡𝑒𝑑 − 𝐼𝑎𝑏𝑠𝑜𝑟𝑏𝑒𝑑 and 𝜑(𝑡) =

10.2. Advanced Simulation 325

Page 330: VSim In Depth

VSim In Depth, Release 8.2.1

∫��(𝑡)𝑑𝑟. Both can be measured in Vorpal via History blocks. Equations of current and voltage are solved for two

unknowns 𝑄𝑐(𝑡) and 𝑄(𝑡). Both quantities determine the status of the external circuit and the boundary condition onthe electrode.

The voltage equation is solved for capacitor charge 𝑄𝑐 at time step n as 𝑄𝑛𝑐 = 𝑉 (𝑛)−𝜑𝑛−𝐾𝑛

𝛼0, where

𝐾𝑛 = 𝛼1𝑄𝑛−1𝑐 + 𝛼2𝑄

𝑛−2𝑐 + 𝛼3𝑄

𝑛−3𝑐 + 𝛼4𝑄

𝑛−4𝑐

𝛼0 = 94

𝐿Δ𝑡2 + 3

2𝑅Δ𝑡 + 1

𝐶

𝛼1 = −6 𝐿Δ𝑡2 − 2 𝑅

Δ𝑡

𝛼2 = 112

𝐿Δ𝑡2 + 1

2𝑅Δ𝑡

𝛼3 = −2 𝐿Δ𝑡2

𝛼4 = 14

𝐿Δ𝑡2

The self-consistent solution for charges on the electrode is 𝑄𝑛 = 𝑄𝑛−2 + 𝐼𝑛−1𝑐𝑜𝑛𝑣 · 2∆𝑡 + 𝑄𝑛

𝑐 − 𝑄𝑛−2𝑐 . Both the

potential 𝜑𝑛 and convective current 𝐼𝑛𝑐𝑜𝑛𝑣 can be measured in Vorpal. Equations of voltage and currents are solvedwith UserFuncUpdater in Vorpal to obtain the electrode charge 𝑄𝑛 at each time step. 𝑄𝑛 is then coupled with fieldequation to find the total electric field self-consistently in the system as ��𝑡𝑜𝑡(𝑡) = ��(𝑡) + 𝑄𝑛

𝑄0��0. Beside the Courant

stability condition that is required by the electromagnetic solver, the time step ∆𝑡 should also follow certain constrainsdue to external circuits as discussed in reference2.

Simulation Procedures

Based on the above algorithm, a simulation with external circuit needs two stage execution. The first stage calculates��0 and 𝑄0 that are used in the second stage, where the actual simulation is carried out.

Stage One of the simulation

The first stage runs a Poisson solver with unit potential in vacuum for only one time step to obtain the electric field��0 and the charge on electrode 𝑄0. As the electrodes are represented by GridBoundary, the Poisson solver looks asfollowing

############ Electrostatic Poisson solver with GridBoundary###########<EmField myESField>kind = yeeStaticEmField

# set the grid boundarygridBoundary = plates

# Set potential on the grid boundary<STFunc boundaryFunc>

kind = expressionexpression = 1.0*phiFunc(x,y,z)

</STFunc>

<Solver mysolver>kind = bicgstabprecond = multigrid

2 J.P. Verboncoeur, M. V. Alves, V. Vahedi and C.K. Birdsall, Journal of Computational Physics 104, 321-328 (1993).

326 Chapter 10. Advanced Concepts

Page 331: VSim In Depth

VSim In Depth, Release 8.2.1

smoother = GaussSeidelnLevels = 7tolerance = 1.0e-10output = nonedumpPotential = true

</Solver>

</EmField>

The total charge on one electrode, such as the cathode used in this example, is calculated with cellFunHist with thefollowing code.

# This is the total charge on the left plate (cathode)# Its value is important and used for subsequent simulations# Test its value for convergence<History totalQ>kind = cellFuncHistfuncLookupScope = myFieldsreduceMethod = sumlowerBounds = [0 0 0]upperBounds = [$NX/2$ NY NZ]

<Expression applySteps>expression = (mod(n, 1) == 0)

</Expression>

<UserFunc histCalc>kind = expression

<CellFunc unitNormal>kind = gridBoundaryFuncgridBoundary = platesresult = surfaceOutwardUnitNormal3D

</CellFunc>

<CellFunc surfacePos>kind = gridBoundaryFuncgridBoundary = platesresult = surfaceCenter

</CellFunc>

<CellFunc dArea>kind = gridBoundaryFuncgridBoundary = platesresult = surfaceArea

</CellFunc>

<SpaceFunc E>kind = fieldFuncresult = fieldValuefield = myESField.YeeStaticElecFldinterpolationOrder = 1gridBoundary = platespolation = fromInOrOutside# the following option is not usually recommended#boundaryCondition = electricAtPEC

</SpaceFunc>

10.2. Advanced Simulation 327

Page 332: VSim In Depth

VSim In Depth, Release 8.2.1

expression = -1.0 * sum(unitNormal(cell) * E(surfacePos(cell))) *→˓EPSILON0 * dArea(cell)</UserFunc>

resultVecDescriptions = ["sum of total charge"]# following is a rough memory size (in MB) that can always be# obtained: it's (very) small here for testing; normally it's best to# use the default value.maxMemChunkSize = 9.6e-5 # about 100 B# to use such a small value for testing, we need to set the followingallowSmallMaxMemChunkSize = truecheckForUnaccessedAttribs = 2

</History>

After the run of this first stage, totalQ (𝑄0) is read from the hdf5 file for History. It values, together with the electro-static field (YeeStaticElecFldTrilinos), are used for stage two.

Stage Two of the Simulation

Stage two is to run the actual simulation that is coupled with external circuit. The convective current at the cathode ismeasured with the following two History blocks for emitted and absorbed currents.

<History cathodeEmitCurrent>kind = speciesCurrEmitspecies = [electrons]ptclEmitter = electrons.psource

</History>

<History cathodeAbsCurrent>kind = speciesCurrAbsspecies = [electrons]ptclAbsorbers = [cathodeAbs]

</History>

The electrostatic field at unit potential calculated from stage one is imported to an edge field name unitE0. It isimported from hdf5 file and only needs to update once at the beginning of the simulation.

<FieldUpdater initunitE0Updater>kind = importFromFileUpdaterfileName = "./externalCircuit0_YeeStaticElecFldTrilinos_1.h5"dataset = "YeeStaticElecFldTrilinos"writeFields = [unitE0]writeComponents = [0 1 2]lowerBounds = [0 0 0]upperBounds = [NX1 NY1 NZ1]

</FieldUpdater>

Charges on the capacitor of external circuit and one of the electrodes are updated via two updaters that solve ex-ternal circuit voltage and current equations. Notice that Q0 used in the chargeQUpdater is obtained form stage onesimulation.

# This updated the Q at the capacitor C at time step n# according to the external circuit voltage equation (Kirchoff's voltage law)# Here the cuircuit is assumed to a general series RLC<FieldUpdater capacitorQUpdater>kind = userFuncUpdater

328 Chapter 10. Advanced Concepts

Page 333: VSim In Depth

VSim In Depth, Release 8.2.1

lowerBounds = [0 0 0]upperBounds = [NX1 NY1 NZ1]

readFields = [phiField capacitorQnm1 capacitorQnm2 capacitorQnm3→˓capacitorQnm4]readComponents = [0 0 0 0 0]readFieldVarNames = [phi qnm1 qnm2 qnm3 qnm4]

writeFields = [capacitorQn]writeComponents = [0]maxNumEvals = 64

<UserFunc updateFunction>kind = expression$alpha0 = 2.25*L/DT/DT + 1.5*R/DT + 1/C$alpha1 = -6.0*L/DT/DT - 2.0*R/DT$alpha2 = 5.5*L/DT/DT + 0.5*R/DT$alpha3 = -2.0*L/DT/DT$alpha4 = 0.25*L/DT/DTexpression = (Vsource((n)*dt) - phi - alpha1*qnm1 - alpha2*qnm2 -

→˓alpha3*qnm3 - alpha4*qnm4) / alpha0</UserFunc>

</FieldUpdater>

<FieldUpdater chargeQUpdater>kind = userFuncUpdaterlowerBounds = [0 0 0]upperBounds = [NX1 NY1 NZ1]

readFields = [totalQnm2 capacitorQn capacitorQnm2]readComponents = [0 0 0]readFieldVarNames = [qnm2 qcn qcnm2]

writeFields = [totalQn]writeComponents = [0]maxNumEvals = 64

<UserFunc updateFunction>kind = expressionexpression = qnm2 + (qcn - qcnm2) - 2.0*dt*(emitI - absI)

</UserFunc></FieldUpdater>

Assuming both electrodes are perfect electric conductors, edgeE and faceB are solved with regular Faraday, Ampereand Dey-Mittra updaters. Combining edgeE with scaled unitE, we obtain the totalE field that is use to advance chargedparticles dynamics via Lorenz force together with faceB.

<FieldUpdater totalEUpdater>kind = userFuncUpdaterlowerBounds = [0 0 0]upperBounds = [NX1 NY1 NZ1]

readFields = [edgeE edgeE edgeE unitE0 unitE0 unitE0 totalQn]readComponents = [0 1 2 0 1 2 0]readFieldVarNames = [EX EY EZ E0X E0Y E0Z QN]

writeFields = [totalE totalE totalE]

10.2. Advanced Simulation 329

Page 334: VSim In Depth

VSim In Depth, Release 8.2.1

writeComponents = [0 1 2]maxNumEvals = 64

<UserFunc updateFunction>kind = expressionexpression = tensorProd(EX, EY, EZ) + tensorProd(E0X, E0Y, E0Z) * QN / Q0

</UserFunc></FieldUpdater>

Notes for external circuit

UserFuncs are heavily used in the external circuit module. Users are suggested to read relevant sections about User-Funcs. In the capacitorQUpdater, phi is measured via pseudopotential and read into a field via historySTFunc. Fortheir usage, please refer to the sections about feedback and historySTFunc in VSim Reference.

10.3 Output

10.3.1 HDF5 Format Vorpal Output Files

Hierarchical Data Format Version 5 (HDF5) is a library and file format for storing graphical and numerical data andfor transferring that data between computers. Vorpal and VSimComposer outputs data in HDF5 format.

The Hierarchical Data Format was developed by the National Center for Supercomputing Applications at the Uni-versity of Illinois at Urbana-Champaign. For more information about HDF5, please see the web page at: http://hdfgroup.org/HDF5

HDF5 Files

The VSim computational engine (Vorpal) outputs data in HDF5 format files that have .h5 suffixes.

Vorpal produces one HDF5 file for each field or species at each dump time. For example, if the simulation parameternsteps = 100 and the simulation parameter dumpPeriodicity = 10, Vorpal dumps data 10 times during thesimulation and outputs a total of 10 HDF5 files for each field or species while running the simulation.

For more information about HDF5, see: http://hdfgroup.org/HDF5

Change the Names of Output Files

If you want to change the names of the output files, which include the .h5 files, you can specify the -o output optionwhen you run Vorpal.

For example, you want to replace emPlaneWave with emPlaneWaveTest1 in the names of the emPlaneWavesimulation’s output files. Run Vorpal from the command line using this command:

vorpal -i emPlaneWave.in -o emPlaneWaveTest1

The output files will be:

• emPlaneWaveTest1_all_1.txt

• emPlaneWaveTest1_comms_0.txt

• emPlaneWaveTest1_completed.txt

330 Chapter 10. Advanced Concepts

Page 335: VSim In Depth

VSim In Depth, Release 8.2.1

• emPlaneWaveTest1_dumpedobjs_0.txt

• emPlaneWaveTest1_electrons_1.h5

• emPlaneWaveTest1_Globals_1.h5

• emPlaneWaveTest1_SumRhoJ_1.h5

• emPlaneWaveTest1_universe_1.h5

• emPlaneWaveTest1_YeeStaticElecField_1.h5

Display the Content of .h5 Files

The h5dump utility converts the binary data in .h5 files into human-readable ASCII data in .txt files.

The h5dump utility is available for all the platforms on which Vorpal runs. You can download the utility from:http://hdfgroup.org/HDF5

The basic command is:

h5dump -o output_file_name.txt your_h5_file.h5

To convert the emPlaneWave_electrons_1.h5 to ASCII text format, use this command:

h5dump -o emPlaneWave_electrons_1.txt emPlaneWave_electrons_1.h5

For information about HDF5 and the h5dump utility, see the HDF5 User’s Guide and HDF5 Reference Manual,which are available at: http://www.hdfgroup.org/HDF5/doc/index.html

General Structure of Simulation Output .h5 Files

For each type of output file below, main data entries within that output file are displayed as a list of fields at thesame level within the list. For those data fields within an output file that contain one or more subcategories of data,subcategories appear in an indented list below the main data category to which the subcategories apply.

Type of Output File: Globals

compGridGlobalrunInfotime

Type of Output File: SumRhoJ

SumRhoJint array [NX NY NZ 4]SumRhoJ[0] = Rho, charge densitySumRhoJ[1] = JxSumRhoJ[2] = JySumRhoJ[3] = Jz

compGridGlobalcompGridGlobalLimitsrunInfotime

Type of Output File: Fluid

10.3. Output 331

Page 336: VSim In Depth

VSim In Depth, Release 8.2.1

NeutralGasNameint array [NX NY NZ 1]NeutralGasName[0] = Density

compGridGlobalcompGridGlobalLimitsrunInfotime

Type of Output File: comboEmField

comboEmFieldint array [NX NY NZ 6]comboEmField[0] = ExcomboEmField[1] = EycomboEmField[2] = EzcomboEmField[3] = BxcomboEmField[4] = BycomboEmField[5] = Bz

compGridGlobalcompGridGlobalLimitsrunInfotime

Type of Output Files: YeeStaticElecFldTrilinos

YeeStaticElecFldTrilinosint array [NX NY NZ 3]YeeStaticElecFldTrilinos[0] = ExYeeStaticElecFldTrilinos[1] = EyYeeStaticElecFldTrilinos[2] = Ez

compGridGlobalcompGridGlobalLimitsderivedVariablesrunInfotime

Type of Output Files: YeeStaticElecFldTrilinosPotential

YeeStaticElecFldTrilinosPotentialint array [NX NY NZ 1]YeeStaticElecFldTrilinosPotential[0] = Electrostatic Potential, Phi

compGridGlobalcompGridGlobalLimitsrunInfotime

Type of Output Files: emMultiField – ElecMultiField

ElecMultiFieldint array [NX NY NZ 3]ElecMultiField[0] = ExElecMultiField[1] = EyElecMultiField[2] = Ez

compGridGlobalcompGridGlobalLimitsderivedVariablesrunInfotime

332 Chapter 10. Advanced Concepts

Page 337: VSim In Depth

VSim In Depth, Release 8.2.1

Type of Output Files: emMultiField – MagMultiField

MagMultiFieldint array [NX NY NZ 3]MagMultiField[0] = BxMagMultiField[1] = ByMagMultiField[2] = Bz

compGridGlobalcompGridGlobalLimitsderivedVariablesrunInfotime

Type of Output File: GridBoundary name

nameint array [NX NY NZ 2]name[0] = true (1) or false (0) is the lower left front corner inside or not?name[1] = true (1) or false (0) is the cell center inside or not?

nameLargeBndryFacesnameLargeFaceFracsnameSmallBndryFacesnameSmallFaceFracsnameStairStepBndryEdgesDatanameStairStepBndryFacesDatacompGridGlobalcompGridGlobalLimitsderivedVariablespolyrunInfotime

Type of Output File: universe

globalGridGlobalglobalGridGlobalLimitsderivedVariablespolyrunInfotimeuniverse

int array [NX NY NZ 2]

Type of Output File: history

runInfohistoryName1historyName2

Note: These historyName arrays contain time data pertaining to the type of history chosen in the input file.

Type of Output File: species

speciesint array [NX NY NZ 6]species[0] = x positionspecies[1] = y position

10.3. Output 333

Page 338: VSim In Depth

VSim In Depth, Release 8.2.1

species[2] = z positionspecies[3] = x velocityspecies[4] = y velocityspecies[5] = z velocity

compGridGlobalLimitsrunInfotime

Note: The information above is representative of 3D data. The actual number of elements in an array may varydepending on the dimensionality of the simulation. The number of elements in a species output file will also varybased on the type of species used. For more information on the output of species data, see the next section.

Columns in Particle Simulation .h5 Output Files

Below is a table displaying how the columns in particle simulation .h5 output files for various species kinds corre-spond to the columns that can be seen in the .h5 file when the file is opened using a tool such as HDFView. HDFViewmay be downloaded for free from the HDF Group at http://www.hdfgroup.org/hdf-java-html/hdfview/. HDFView dis-tributions are available for 32-bit and 64-bit Linux, Mac, and Windows platforms.

Table 10.1: Legend

NDIM Number of Dimensions: 1, 2, or 3Dimension Notation

1D 2D 3Dx x y x y z1D 1D,[2D] 1D,[2D,[3D]]

Cylindrical CoordinatesPolar u0, u1, u2 r, phi, zCylindrical u0, u1, u2 z, r, phiTubular u0, u1, u2 phi, z, r

Momentum/Mass Notation Conventionmomentum/mass = gamma*v = P

gamma*vx:Px gamma*vy: Py gamma*vz: Pz

Columns in .h5 in Particle Simulation Output Files

334 Chapter 10. Advanced Concepts

Page 339: VSim In Depth

VSim In Depth, Release 8.2.1

Species Number of Columns Comma-separated ColumnscmplxRelBorisDF 5 + NDIM x,[y,[z]]Px, Py, Pz, real weight, imaginary weightenvBoris 5 + NDIM x,[y,[z]]Px, Py, Pz, tag, weightfreeRel 3 + NDIM x,[y,[z]]Px, Py, PzfreeRelVW 4 + NDIM x,[y,[z]]Px, Py, Pz, weightnoMove 3 + NDIM x,[y,[z]]Px, Py, PznoMoveVW 4 + NDIM x,[y,[z]]Px, Py, Pz, weightnonRelBoris 3 + NDIM x,[y,[z]]Px, Py, PznonRelEs 3 + NDIM x,[y,[z]]Px, Py, PzrelBoris 3 + NDIM x,[y,[z]]Px, Py, PzrelBorisBallisticVW 4 + NDIM x,[y,[z]]Px, Py, Pz, weightrelBorisCyl 3 + NDIM u0,[u1,[u2,]]P0, P1, P2 (see Legend)relBorisDF 4 + NDIM x,[y,[z]]Px, Py, Pz, weightrelBorisEffMassExtd 2 + 3(NDIM always 3) x, y, z, Px, Py, Pz, valley index, weight (always 1)relBorisFuncVW 4 + NDIM x,[y,[z]]Px, Py, Pz, weightrelBorisTagged 4 + NDIM x,[y,[z]]Px, Py, Pz, tagrelBorisVW 4 + NDIM x,[y,[z]]Px, Py, Pz, weightrelBorisVWTagged 5 + NDIM x,[y,[z]]Px, Py, Pz, tag, weightrelBorisVWScale 6 + NDIM x,[y,[z]]Px, Py, Pz, tag, scale parameter, weightcell 3 + NDIM x,[y,[z]]Px, Py, Pzcell(VW) 4 + NDIM x,[y,[z]]Px, Py, Pz, weightcell(tagged) 4 + NDIM x,[y,[z]]Px, Py, Pz, tagcell(VW, tagged) 5 + NDIM x,[y,[z]]Px, Py, Pz, tag, weight

Note: The cell species (kind = cell) set variable weight (VW) and tagging with thevariableWeightParticle and taggedParticle parameters.

HDFView Particle Simulation .h5 Output File Illustration

Below is an HDFView display of a Vorpal species .h5 output file. The annotated columns within the illustrated outputfile correspond to those presented in the table Columns in .h5 in Particle Simulation Output Files. HDFView may bedownloaded for free from the HDF Group at:

http://www.hdfgroup.org/hdf-java-html/hdfview/

10.3.2 Particle Postprocessing

VSim includes a separate executable utility for basic particle reduction that can greatly speed the analysis of particledata. While the Cartesian structure of Vorpal field data allows it to be easily selected for analysis (for instance, throughslicing), Vorpal particle data is unstructured and particles have no guaranteed order in the data set. Therefore, analysisoften requires examining every particle. For very large simulations, which can run into the hundreds of millions ofparticles and produce gigabytes of data in each dump, this can be quite time consuming. The postprocessing utilitygreatly speeds this process by performing the initial analysis and reduction of particle data in parallel.

The postprocessing utility can apply two kinds of data reduction: Downselection of particle data based on user-specified criteria, and binning particle data into one or two dimensional histograms. While these types of data reductionare simple, they can be used effectively to reduce the particle data for each dump from many gigabytes to a manageablesize for further analysis on a single processor.

The postprocessing utility is an executable that is installed in the same directory as the Vorpal executables. You useit in much the same manner as you use the Vorpal command-line executable: You create an input file with the .preextension to specify the types and parameters of the data reduction and then run the executable.

10.3. Output 335

Page 340: VSim In Depth

VSim In Depth, Release 8.2.1

Fig. 10.15: HDFView display of a Vorpal species .h5 output file.

336 Chapter 10. Advanced Concepts

Page 341: VSim In Depth

VSim In Depth, Release 8.2.1

Preparing the data reduction input file

The data reduction input file uses the same basic syntax as Vorpal input files: attributes specified in the form name =value, in many cases organized into blocks. There is a single global attribute, a type of block describing a particlespecies, and two types of blocks corresponding to the two possible types of data reduction.

The global attribute, runName, specifies the name of the Vorpal run which produced the data and which prefixes thedata files. For instance, if we are postprocessing a laser-plasma acceleration simulation named lpa, we would includethis attribute as

runName = lpa

The number of dimensions should match that in the run which produced the data.

$NDIM = 2 # The number of dimensions in lpa is 2, so we set a variable for the numberof dimensions accordingly.

The Species block specifies a particle species to use for data reduction. The block must be named according to thename of the species. There is a single optional attribute, weightIndex, which gives the index of the particle weightin the data set for the case of variably-weighted particles. It should be omitted for constant-weight particles. So if wewish to reduce the electrons data set, and the weight is stored at index 7 in the data set (for instance, with a tagged,weighted species in a 3D run), we would use

<Species electrons>weightIndex = NDIM + 4

</Species>

In this example, the utility would search for files with names lpa_electrons_*.h5 to reduce. For histogramming(see below), the data would be weighted according to the values at index 7.

Use a ParticleSelector block to specify downselection of a particle data set. You can select particles for whichthe variable at the specified index lies in the specified interval. In our example, if we wish to select particles whoserelativistic longitudinal velocity is greater than 3 × 107 m/s, we would use

<ParticleSelector uxSelector>species = electronselement = NDIMinterval = [3.0e7 1.0e20]

</ParticleSelector>

Here, we have specified selection from the electrons species particles whose longitudinal velocity, stored at el-ement 3 in the data set, has value greater than 3 × 107. Note that we have given 1020 as the upper bound to theinterval since we do not wish there to be a maximum limit, and 1020 is greater than any realistic particle velocity inthis simulation. The selected particles are then written to the files lpa_uxSelector_*.h5, with one output filecorresponding to each data file for that species.

Use a ParticleHistogram to specify generation of a histogram from particle data. You specify the axes to binand the number of bins to use in each direction. For instance:

<ParticleHistogram phaseSpace>species = electronsaxes = [0 NDIM]numBins = [300 300]

</ParticleHistogram>

This specifies creating two dimensional histograms of the variables at indices 0 and 3 in the electrons data set; sincethese correspond to longitudinal position and velocity, this produces phase space histograms. We have specified 300bins in each direction. Note that if the weightIndex option was given in the Species block, the values at that

10.3. Output 337

Page 342: VSim In Depth

VSim In Depth, Release 8.2.1

index would be used to weight the histogram. One dimensional histograms work the same way, except that only one el-ement is given in the axes and numBins vectors. The histograms will be written to the files lpa_phaseSpace_*.h5, with one output file corresponding to each data file for that species. Histogram output files are in the same formatas Vorpal field data files.

Running the data reduction executable

Once the input file is prepared, you execute the postprocessing utility from the command line in much the same way asVorpal. The serial executable is called ptclPostprocser and the parallel executable ptclPostproc, and thesereside in the same location as the Vorpal executables. The one difference with Vorpal is that you use the -d option tospecify the directory where the original data resides. For instance, if the above syntax was in the file lpaPostproc.pre, and the original data are in the directory ../lpa, you can run the data reduction in parallel on 64 cores asfollows:

<VORPAL_BIN_DIR>/mpiexec -np 64 <VORPAL_BIN_DIR>/ptclPostproc -i lpaPostproc.pre -d ..→˓/lpa

All the reduced data files are then produced in the directory from which the postprocessing utility is run.

338 Chapter 10. Advanced Concepts

Page 343: VSim In Depth

CHAPTER

ELEVEN

TROUBLESHOOTING AND FAQ

11.1 FAQ for VSimComposer Visual Setup

11.1.1 Why can’t I get my cylindrical EM simulation set up?

At the release of VSim 8.0, cylindrical EM is not yet implemented. To do these types of simulations, you must revertback to text-based setup files.

11.1.2 Why do I have errant lines in my CSG geometry after I run VSim? (version8.0)

Fixed in release 8.1

Even though your CSG geometry looks fine in visual setup, sometimes errant pieces will show up in visualizationafter your simulation has been run. This is due to some known issues when writing the stl which is then read in to theVorpal engine.

The way around this, for the time being, is to offset your grid by a small fraction of it’s size so that the geometry doesnot line exactly on a grid cell. For instance, xMin = -0.500001

11.1.3 Why does my geometry look fine in serial, but not in parallel? (version 8.0)

Fixed in release 8.1

Occasionally, for parallel runs, the stl reader can spuriously set some regions outside of objects to being inside. Whenthis happens, it is manifest in the visualization of the corresponding geometry field in Data Overview. In all casesobserved so far, this has been fixed by offsetting the grid a small amount, changing the number of cells, and/orchanging the number of parallel processes.

11.1.4 Why is my dielectric being ignored in my electrostatic simulation?

The implementation of dielectrics in the visual set up interface is restricted to electromagnetic solves only. Using adielectric Material with a Geometry and an electrostatic field solve will not work.

In order to do an electrostatic solve with a dielectric, you must use the text-based setup.

339

Page 344: VSim In Depth

VSim In Depth, Release 8.2.1

11.2 Troubleshooting VSimComposer Visualization

11.2.1 On Windows, VSimComposer Claims No Data Found Even Though it Exists

It is possible you are trying to visualize data from a UNC-style path.

On Windows machines, data inside a directory following Universal Naming Convention (UNC), e.g., \machinedirec-toryfile, cannot be visualized using VisIt, the underlying visualization tool to VSimComposer. UNC style paths arenot supported. Instead, map the UNC path to a letter drive on the machine.

11.3 Troubleshooting Electrostatic Simulations

11.3.1 The Simulation Does Not Finish Properly

The most common cause of crashes is improperly set up particle boundaries. The particle boundaries must completelysurround the space in which particles are loaded. Otherwise particles can drift out of the grid and try to reference fieldsthat do not exist. This leads to a Vorpal segmentation fault.

Another possible reason for an electrostatic simulation not finishing properly is that a particle has crossed more thanone cell in a time step. This could allow the particle to pass through a particle sink without being absorbed.

• One solution is to reduce the duration of the time step.

• Another solution is to limit the number of cells a particle can cross in one time step by artificially reducing thevelocity of high speed particles. See maxcellxing

It could be that the definition of the Particle Species is incorrect.

The following Species input block is not defined correctly:

<Species electrons>kind = nonRelBorisemField = myZeroField...

</Species>

• The problem: The input block does not specify mass and charge.

• The result: The simulation runs normally with no complaints. The default mass and charge are those of apositron.

• The solution: Include the mass and charge of your species every time they are defined.

11.3.2 The Electrostatic Solver Does Not Converge

If the electrostatic solver does not converge, this often indicates a problem with the setup. The matrix can becomesingular in a fully periodic system. For solutions, see the section Fully Periodic Systems.

340 Chapter 11. Troubleshooting and FAQ

Page 345: VSim In Depth

VSim In Depth, Release 8.2.1

11.4 Troubleshooting Electromagnetic Simulations

11.4.1 The Simulation Does Not Finish Properly

The most common cause of crashes is improperly set up particle boundaries. The particle boundaries must completelysurround the space in which particles are loaded. Otherwise particles can drift out of the grid and try to reference fieldsthat do not exist. This leads to a Vorpal segmentation fault.

A common problem with electromagnetic simulation is not following the Courant condition. The Courant conditionstates roughly that the time step must be small enough that a light wave cannot cross more than one cell in a singletime step.

11.4.2 The Output Shows an Unexpected High-Frequency or Checkerboard Pattern

These patterns can be symptoms of an instability resulting from violating the Courant condition. Roughly stated, theCourant condition states that the time step must be small enough that a light wave cannot cross more than one cell ina single time step.

11.5 Troubleshooting plasma density

If applyTimes is set, and includes time t=0 in the range, particles may be loaded both during initializationand in the zeroth time step of the model, potentially giving twice the density you want.

Use together with a history of kind=speciesNumPhysical and compare the total population to the numberof particles you expected.

Use together with the computePtclNumDensity script to check the overall density of the loaded particles.

11.6 Troubleshooting performance

VSim is designed to optimally use the computational hardware you have available, whether a laptop or aleadership class supercomputing facility.

It achieves this through the use of advanced algorithms, but this does not guarantee any given simulationwill run as fast as possible. This document outlines some simple checks which may aid speeding up asimulation.

On the one hand, there are different types of algorithms for field solves, particle movers and monte-carlo,and these may all scale up in slightly different ways, and require different amounts of inter- processorcommunication for large parallel simulations. If there are lots of diagnostics, these may also impactperformance.

Firstly, it helps to understand which parts of the simulation are taking the most time. The best wayto do this is to remove elements of the simulation one at a time, and to assess the difference in speed.Having measured performance of field solves, particle pushes (if applicable), monte carlo interactions (ifapplicable) and history objects, it may be possible to simplify some of these, for example by adjusting thenumber of macroparticles per physical particle.

In general one need not dump the fields and particles more often than is necessary as this will lead to slowvisualisation, and the slowing down of the simulation while the data is written.

11.4. Troubleshooting Electromagnetic Simulations 341

Page 346: VSim In Depth

VSim In Depth, Release 8.2.1

11.6.1 Electromagnetic solves

Electromagnetic solves tend to be bound by computation and their ability to pass fields on their boundariesacross the network. As a rule of thumb - performance tends not to increase well when the domain oneach processor is smaller than 40x40x40 - but this limit will depend on the relative performance of yournetwork fabric and CPU. Also, cells ourside perfect electrical conductor take longer than inside, so it cansometimes be worth adjusting the domain decomposition strategy to ensure the load is balanced equally.Minimize the regions are over which any MAL or PML boundary conditions are applied, as these will becomparatively slow compared with a normal cell update.

11.6.2 Electrostatic solves

Electrostatic solves can be very memory intensive. Memory contention can be a limiting factor here, sothere may be a ‘sweet spot’ in terms of not only the total number of processors to use, but the number ofprocessors per node. System adminstrators may be able to provide diagnostic tools to help monitor this be-haviour. With fixed number of nodes, varying the domain size may also help understand the performancebottlenecks.

11.6.3 Particle balancing

Only in a few kinds of simulation are particles evenly distributed throughout the simulation domain forall times, and their distributions will likely vary from species to species. The ‘binning’ tool in VSim-Composer may be used to count the number of particles vs x,y,z, and again a domain decomposition willsometimes help ensure the load is balanced optimally. It can help to temporarily add extra diagnostics tomeasure total populations of macroparticles for all species as they vary through your simulation, and tofocus on those with the most macroparticles.

If the number of macroparticles of some species is changing by many orders of magnitude, consider astrategy which includes macroparticle combining or splitting. See: montecarlointeractions-interactions-nullselfcombination-kind

For densities that are uniformly high, and with conseuqent low mean free path, consider whether afluid/hybrid approach might be better.

11.6.4 Particle interactions

In anything other than a very simple plasma with only a few interactions and species present, the time torun discharge simulations is often dominated by the computation of interactions between the particles.

The most important thing is to make sure you are using the right set of interactions to describe yourplasma. If you are uncertain, consider running a global model to analyze the reaction paths and ensureinsignificant paths are eliminated from the simulation.

Monte-carlo type algorithms for interactions should be set such that the timestep is small enough thatinteraction probailities are always small as advised in Monte Carlo Interactions Package.

Histories store their data in RAM inbetween data dumps, and can write very large datasets. Some historiesneed to do non-trivial amounts of computation each time step.

11.6.5 Configuration issues

The installer Tech-X provides can be expected to work well out of the box on desktop and high perfor-mance computing systems.

342 Chapter 11. Troubleshooting and FAQ

Page 347: VSim In Depth

VSim In Depth, Release 8.2.1

HPC systems often have high performance parallel systems. Commonly these are set up differently fromyour home area, and you will need to ensure you are running with your data being output to a specificpartition. Check the cluster documentation for more information.

HPC sytems are sometimes be set configured with a differnt MPI in the environment set up by the queuesystem to VSim’s requried mpich MPI. In rare cases the MPI installation provided by VSim can pickup the wrong network card or fail to use the correct infiniband driver (normally where this has beencustomized heavily on those clusters). This will likely manifest as very poor parallel performance - forexample with a simulation with sixteen cores one node running very much faster than a simulation onthirty-two cores on two nodes (subject to the scaling advice above). In these cases we recommend youcontact Tech-X support at [email protected] for advice. Modification of the environment is non-trivialand may have unexpected consequences.

11.7 Troubleshooting windows permissions

If you see permission errors, try running the command prompt as administrator by right clicking theprompt and clicking “Run as administrator”.

11.7. Troubleshooting windows permissions 343

Page 348: VSim In Depth

VSim In Depth, Release 8.2.1

344 Chapter 11. Troubleshooting and FAQ

Page 349: VSim In Depth

CHAPTER

TWELVE

REFERENCES

Further reading and terminology definitions:

12.1 Bibliography

[1] Birdsall, C. K., and Langdon, A. B., Plasma Physics Via Computer Simulation. Adam Hilger, 1991. [2] Courant,R., Friedrichs, K., and Lewy, H., “On the partial difference equations of mathematical physics,” IBM Journal, p. 215,March 1967. This article is a publication in English of an article originally published in German: Über die partiellenDifferenzengleichungen der mathematischen Physik, Mathematische Annalen, vol. 100, no. 1, pp. 32-74, 1928. [3]Hockney, R.W., and Eastwood, J. W., Computer Simulation Using Particles. Adam Hilger, 1988.

[4] Kutasi, K., and Donko, Z., “Hybrid model of a plane-parallel hollow-cathode discharge,” Journal of Physics D:Applied Physics, vol. 33, pp. 1081-1089, 2000.

[5] Messmer, P., and Bruhwiler, D.L., “A parallel electrostatic solver for the VORPAL code,” Computer PhysicsCommunications, vol. 164, pp. 118-121, 2004.

[6] Nieter, C., and Cary, J. R., “VORPAL: a versatile plasma simulation code,” Journal of Computational Physics, vol.196, pp. 448-473, 2004.

[7] Reiser, M., Theory and Design of Charged Particle Beams. Wiley-Interscience, 1994.

[8] Villasenor, J., and Buneman, O., “Rigorous charge conservation for local electromagnetic-field solvers,” ComputerPhysics Communications, vol. 69, p. 306-316, 1992.

[9] Xiang, N., Cary, J. R., Barnes, D. C., and Carlsson, J. A., “Low-noise electromagnetic df particle-in-cell simulationof electron bernstein waves,” Physics of Plasmas, vol. 13, pp. 062111.1-062111.13, 2006.

[10]Yee, K. S., “Numerical solution of initial boundary value problems involving maxwell’s equations in isotropicmedia,” IEEE Transaction of Antennas and Propagation, vol. 14, p. 302-307, 1966.

12.2 Glossary

domain The rectangular Cartesian grid. The physical domain is the grid specified by a user. The extended domain isthe grid with guard cells added by Vorpal.

extended domain See domain.

FDTD Finite-difference time-domain. The FDTD method is a technique for solving problems in electromagnetics.

float A floating-point number.

345

Page 350: VSim In Depth

VSim In Depth, Release 8.2.1

guard cell A cell located outside the user-defined simulation grid that Vorpal adds for parallel processing and othercomputational purposes. Charges cannot be deposited in guard cells, but you can use guard cells when youdescribe boundary conditions.

HDF5 Hierarchical Data Format Version 5. A library and file format, developed by the National Center for Super-computing Applications at the University of Illinois at Urbana-Champaign, for storing graphical and numericaldata and for transferring that data between computers. Vorpal and VSimComposer output data in HDF5 FormatVorpal Output Files.

input block An input block is an object consisting of parameters. Input blocks can be nested within other input blocks.For example, input blocks for boundary conditions are nested within the input block for an electromagnetic field.

input file A Vorpal simulation file, which has a .pre suffix. Users define a simulation and its variables in an input file.VSimComposer then runs the input file through a preprocessor to produce a processed input file.

MPI Message Passing Interface. An application programming interface (API) for communicating between processesexecuting in parallel.

multi-grid pre-conditioner A pre-conditioner that enables a solver to use a hierarchy of grids to solve a partialdifferential equation problem. The multi-grid pre-conditioner applies the results from coarse grids to acceleratethe convergence on the finest grid.

parameter A parameter is a variable value (integer, floating-point number, or text string) that users define to create asimulation.

parse To divide input into parts and determine the meaning of each part.

physical domain See domain.

pre-conditioner An algorithm that works with an electrostatic solver to transfer an original linear system matrix intoa matrix that has better convergence behavior.

processesd input file A Vorpal simulation file, which has a .in suffix. VSimComposer processes the input file toproduce a processed input file.

Python An open-source, interpreted scripting language managed by the Python Software Foundation.

SI units The International System of Units (Le Systeme International d’Unites), which has seven baseunits: meter, kilogram, second, ampere, kelvin, mole, and candela.

solver An algorithm that calculates the results of electrostatic problems.

TxPhysics A cross-platform library of computational modules, provided by Tech-X Corporation, for modelingcharged particles.

• Vorpal™ © 1999-2002 University of Colorado. All rights reserved.

• Vorpal™ © 2002-2017 University of Colorado and Tech-X Corporation. All rights reserved.

• VSim™ except for Vorpal™ is © 2012-2017 Tech-X Corporation. All rights reserved.

For VSim™ licensing details please email [email protected]. All trademarks are the property of theirrespective owners. Redistribution of any VSim™ input files from the VSim™ installation or the VSim™document set, including VSim Quick Start, VSim In Depth, and VSim Reference, is allowed provided thatthis Copyright statement is also included with the redistribution.

346 Chapter 12. References

Page 351: VSim In Depth

BIBLIOGRAPHY

[Cowan] 2. Cowan, et al, “Generalized algorithm for control of numerical dispersion in explicit time-domain elec-tromagnetic simulations” Phys. Rev. ST Accel. Beams 16, 041303 (2013)

347