Script commands as methods#

At the most basic level, you can use PyLumerical to directly invoke Lumerical script commands and interact with the product as the Lumerical Scripting Language would.

This article describes the basic use case for using scripting commands as methods, and common best practices.

Built-in scripting commands#

Overview#

You can use almost all script commands in the Lumerical Scripting Language as methods on your session object in Python. The PyLumerical methods and the Lumerical script commands share the same name, and you can call them directly on the session object once you create it.

For more information on the Lumerical Scripting Language, please see:

Two simple examples are show below. The first example uses Lumerical commands getfdtdindex and stackrt in conjunction with typical math and plotting libraries in Python to simulate and visualize the transmission of a gold thin film illuminated by a plane wave. The second example sets up and runs a simple simulation with a gaussian source and a frequency domain monitor.

Example

For more information on how to install PyLumerical and import the modules, see Installation and getting started for PyLumerical.

import ansys.lumerical.core as lumapi
import numpy as np
import matplotlib.pyplot as plt

with lumapi.FDTD() as fdtd:
    lambda_range = np.linspace(300e-9, 1100e-9, 500)
    c=2.99792458e8
    f_range = c/lambda_range

    # Use the getfdtdindex command to obtain the correct complex index for gold
    au_index = fdtd.getfdtdindex("Au (Gold) - CRC", f_range, np.min(f_range), np.max(f_range))

    # Use the stackrt command to calculate the transmission and reflection
    stackRT_result = fdtd.stackrt(np.transpose(au_index), np.array([10e-9]), f_range)


# Visualize using matplotlib
fig, ax = plt.subplots()
ax.plot(lambda_range*1e9, stackRT_result["Ts"], label="Transmission")
ax.set_xlabel("Wavelength [nm]")
ax.set_ylabel("Transmission")
ax.legend()
plt.show()

Example

import os,sys
import numpy as np
sys.path.append("C:\\Program Files\\Lumerical\\v251\\api\\python\\") # locate lumapi files
import ansys.lumerical.core as lumapi
import matplotlib.pyplot as plt


with lumapi.FDTD() as fdtd:

    # Set up simulation region
    fdtd.addfdtd()
    fdtd.set("x",0)
    fdtd.set("x span",8e-6)
    fdtd.set("y",0)
    fdtd.set("y span",8e-6)
    fdtd.set("z",0.25e-6)
    fdtd.set("z span",0.5e-6)

    # Set up source
    fdtd.addgaussian()
    fdtd.set("injection axis","z")
    fdtd.set("direction","forward")
    fdtd.set("x",0)
    fdtd.set("x span",16e-6)
    fdtd.set("y",0)
    fdtd.set("y span",16e-6)
    fdtd.set("z",0.2e-6)
    fdtd.set("use scalar approximation",1)
    fdtd.set("waist radius w0",2e-6)
    fdtd.set("distance from waist",0)
    fdtd.setglobalsource("wavelength start",1e-6)
    fdtd.setglobalsource("wavelength stop",1e-6)

    # Set up monitor
    fdtd.addpower()
    fdtd.set("monitor type","2D Z-normal")
    fdtd.set("x",0)
    fdtd.set("x span",16e-6)
    fdtd.set("y",0)
    fdtd.set("y span",16e-6)
    fdtd.set("z",0.3e-6)

    # Run simulation
    fdtd.save("fdtd_tutorial.fsp")
    fdtd.run()

Constructor script commands#

You can use many script commands to add simulation objects such simulation regions or geometric regions. These commands typically start with “add”, for example, addrect or addfdtd.

In PyLumerical, you can create simulation objects in many different ways. At a fundamental level, you can create objects and have their properties set like a Lumerical script using set and setnamed.

In addition, PyLumerical also supports assigning properties to object in a way more native to Python, either by creating a dictionary and assigning it to the properties attribute during initialization or using keyword arguments directly. When constructing objects using these methods, you may need to initialize some properties in order, and some properties may overwrite other properties. Therefore, it’s recommended to use an ordered dictionary to ensure that you set these properties as intended.

The examples below show various methods on object construction. For more information regarding adding and manipulating simulation objects, including best practices, see the article on Working with simulation objects. When a property has a space in its name, for example, x span, the name for keyword arguments uses an underscore instead of space, for example, x_span.

Example

These examples create a 3D FDTD region centered at the origin and with a span of 1μm.

Firstly, using the Lumerical script commands:

fdtd = lumapi.FDTD()
fdtd.addfdtd()
fdtd.set("x",0)
fdtd.set("y",0)
fdtd.set("z",0)
fdtd.set("x span",1e-6)
fdtd.set("y span",1e-6)
fdtd.set("z span",1e-6)

The following code creates the FDTD region uses an ordered dictionary to set its properties.

from collections import OrderedDict # Ensure OrderedDict is imported
# import other modules

fdtd = lumapi.FDTD()
props = OrderedDict([("x", 0),("y",0), ("z", 0), ("x span", 1e-6), ("y span", 1e-6), ("z span", 1e-6)])
fdtd.addfdtd(properties = props)

The following code creates the FDTD region using keyword arguments

fdtd = lumapi.FDTD()
fdtd.addfdtd(x=0,y=0,z=0,x_span=1e-6, y_span=1e-6, z_span=1e-6) # Note that the property names where a space was present is replaced by an underscore

For more information regarding adding and manipulating simulation objects, including other ways to interact with these objects and best practices see the article on Working with simulation objects.

Importing custom script commands#

In addition to default script commands, you can also take advantage of the auto-syncing function feature in PyLumerical and import functions that are pre-defined in a Lumerical script file (.lsf file). To import these functions, you can either execute the scripts while constructing the session using the script keyword argument, or manually evaluating the file using the ansys.lumerical.core.FDTD.eval() method.

Example

The following two .lsf files contains custom functions.

MyFunctions.lsf

function helloWorld(){
return "helloworld";
}

function customAdd(a,b){
return a+b;
}

MyFunctions2.lsf

function customMultiply(a,b){
return a*b;
}

The following script imports functions from both custom script files upon session creation.

with lumapi.FDTD(script = ["MyFunctions.lsf", "MyFunctions2.lsf"]) as fdtd:
# From MyFunctions.lsf
print(fdtd.helloWorld())
print(fdtd.customAdd(1,2))
# From MyFunctions2.lsf
print(fdtd.customMultiply(4,5))

Returns

helloworld
3.0
20.0

Non-constructor script commands#

For script commands that needs input arguments, but don’t create simulation objects, you can only use them with position arguments and not keyword arguments.

For example, the following code results in an error, even though the set script command takes property and value as input arguments.

Example

fdtd.addfdtd()
fdtd.set(property = "x span", value = 1e-6)

# Results in an error

The correct usage is the following.

fdtd.addfdtd()
fdtd.set("x span", 1e-6)

This applies also to methods defined in other scripting files that are loaded by first evaluating the script file.

Example

A Lumerical script file named MyConstructor.lsf contains the following function definition.

function constructFDTDandRect(x_input,y_input,z_input){
# This function creates an FDTD and a rectangle region with center coordinates at x, y, and z
addfdtd;
set("x",x_input);
set("y",y_input);
set("z",z_input);

addrect;
set("x",x_input);
set("y",y_input);
set("z",z_input);
}

The following Python driver script causes an error, even though the function defined in the script file have arguments named x_input, y_input, and z_input.

fdtd = lumapi.FDTD()
custom_code = open("MyConstructor.lsf", "r").read()# This assumes the current working directory has a file named “MyConstructor.lsf”. Use os.chdir to change the current working directory if needed.
fdtd.eval(custom_code)
fdtd.constructFDTDandRect(x_input =0,y_input = 0, z_input = 0)

# Results in error

In contrast, the following driver script executes without error, and add both the FDTD region as well as the rectangle.

fdtd = lumapi.FDTD()
custom_code = open("MyConstructor.lsf", "r").read()# This assumes the current working directory has a file named “MyConstructor.lsf”. Use os.chdir to change the current working directory if needed.
fdtd.eval(custom_code)
fdtd.constructFDTDandRect(0,0,0)

Unsupported methods#

While most script commands are available, there are a few categories of commands that aren’t available for use in PyLumerical. For example, certain reserved keywords, such as “c” for the speed of light, are unavailable in Python. If you requires access to these variables, it’s best to either define them in Python, or to use the ansys.lumerical.core.FDTD.eval() method. However, if the ansys.lumerical.core.FDTD.eval() method is used, you should be mindful that the variables in the Python and Lumerical scripting environments are not automatically shared.

Operators

PyLumerical doesn’t overload script operators in the Lumerical Scripting Language, and you can’t use them “as-is” in Python. Use alternatives in Python. The unavailable operators include:

  • Algebraic–For example, * , / , + , - , ^

  • Logical–For example, >= , < , > , & , and , | , or , ! , ~

  • The ? (print, display) operator used to screen and query available results

Local documentation#

For information on the PyLumerical methods from within the environment, Python docstrings are available for Lumerical session objects. This is the simplest way to determine the available script commands, and syntax. This contains information similar to Alphabetical List of Script Commands. You can view the docstring by using the Python built-in function “help” or most ways rich interactive Python shells display docstrings, for example IPython or Jupyter Notebook.

Example

# First, create an FDTD object
fdtd = lumapi.FDTD()

# Then, use the help function to view the docstring
help(fdtd.addfdtd)

Returns

Help on method addfdtd in module lumapi:
addfdtd(self, *args) method of lumapi.FDTD instance
Adds an FDTD solver region to the simulation environment.  The extent of
the solver region determines the simulated volume/area in FDTD
Solutions.
+-----------------------------------+-----------------------------------+
| Syntax                            | Description                       |
+-----------------------------------+-----------------------------------+
| o.addfdtd()                       | Adds an FDTD solver region to the |
|                                   | simulation environment.           |
|                                   |                                   |
|                                   | This function does not return any |
|                                   | data.                             |
+-----------------------------------+-----------------------------------+
See Also
set(), run()
https://kb.lumerical.com/en/ref_scripts_addfdtd.html