MATLAB - Lumerical integrations

This section describes the various ways that MATLAB TM can be used with Lumerical's software.

Script integration

The  MATLAB script integration  feature allows MATLAB commands to be called directly from the Lumerical scripts. This allows you to access MATLAB's powerful analysis and visualization tools while working from within the Lumerical environment.

See  MATLAB integration setup  if you experience any problems using this feature.

MATLAB script integration

The Script Integration feature allows MATLAB commands to be typed directly into the Lumerical script prompt. This provides a very seamless way to take advantage of the full range of MATLAB functions.

Setup instructions and system requirements for the MATLAB script integration feature can be found in the online Knowledge Base. See the MATLAB integration setup section of the Installation Guide.The MATLAB interface functions (matlab, matlabput, matlabget) allow you to work primarily within the Lumerical script environment, but still have access to the full range of MATLAB functions when they are required. For information on supported versions of MATLAB, see the matlab script function description.

The first time one of these functions is called, it will start a MATLAB session and create a connection between the two applications. Once the connection is established, it is possible to transfer data from Lumerical to MATLAB (matlabput), transfer data from MATLAB to Lumerical (matlabget), and run MATLAB commands from the Lumerical script prompt (matlab).

For example, open usr_matlab.fsp, then run usr_matlab_optionA.lsf. A MATLAB session will be opened in the background. The MATLAB coutourf function is used to create a contour plot of the electric field intensity, as shown below. In addition to the contour plot, more advanced text formatting is possible, such as using the Greek letter Mu on the axis labels.

 

MATLAB script integration configuration guide

This article describes how to set up MATLAB script integration features with Lumerical products.

Notes

  • Lumerical does not guarantee that all versions of our products will be compatible with all MATLAB versions on all operating systems (the number of permutations is very large!), although we have found that it works for most customers.
  • Only the 64-bit version of MATLAB is supported.
  • Some releases of MATLAB include newer versions of system libraries than are provided by the operating system.  The new libraries are saved in a private location that only MATLAB can 'see'.  This creates problems for the Matlab script integration since the Lumerical application will use the standard version of the system library while MATLAB will use its private version of the same library. This creates a conflict, which stops the script integration from working. See below for possible solutions.
  • The MATLAB script integration feature requires MATLAB version 2006b to 2019a.

Lumerical to MATLAB script integration 

The MATLAB script integration feature allows MATLAB script functions to be called from within Lumerical's scripts via the matlab, matlabput and matlabget script functions. 

Check feature status

To check the status of the MATLAB script integration feature, go to the Help menu and select Matlab integration status.

mceclip1.png

mceclip0.png

See details below for configuration instructions for your operating system. 

Windows

Step 1

The products should be able to locate the MATLAB libraries.  If they are not in the system library path, you must manually specify their location.

  1. Open the Matlab integration status window from the Help menu.
  2. Use the Select button to manually locate the MATLAB system libraries.
  3. Restart the Product for the change to take effect.

    mceclip2.png

Step 2 

MATLAB must be registered as an automation server on your system before the script integration feature will work. Registration normally occurs during the MATLAB install process, but occasionally the registration fails or is lost.  

In such cases, manual registration is required. Manual registration may also be required when you have multiple versions of MATLAB installed and would like to register MATLAB for the desired version, e.g. if the MATLAB license of one version is not available.

Administrator access is required for these configurations. For more information, please refer to MATLAB documentation.

  1. To register MATLAB, open a MATLAB session and type the following command:
    !matlab /regserver 
  2. The ! operator in MATLAB just executes the remainder of the line at the command prompt, so this is equivalent to running a command below from the Windows command prompt as Administrator,
    "C:\Program Files\MATLAB\<version>\bin\win64\matlab" /regserver
  3. To test the registration, open Lumerical and use one of the MATLAB script integration functions. You can also test the registration within MATLAB by running;
    h = actxserver('Matlab.Application')
    h.Execute('plot(1:10)')
  4. The first command starts a second background instance of MATLAB, very similar to the way our software starts a MATLAB session. The second command sends the plot command from the original MATLAB session to the new MATLAB session. You should see a simple plot window.

Linux

The following two configuration steps are often required to setup the MATLAB script integration on Linux. Occasionally, the third step will be required.

Step 1

The matlab command must be in the path, so if you type 'matlab' at the terminal, the MATLAB application will start. To do this you can either add the folder where you installed MATLAB to your PATH, or you can create a symbolic link to the matlab command in another folder that is already in the path.

$  sudo ln -s /usr/local/MATLAB/<version>/bin/matlab  /usr/bin/matlab
Step 2

Your Lumerical Product must be able to locate the MATLAB libraries.  If they are not in the system library path, you must manually specify their location.

  1. Open the Matlab integration status window from the Help menu.
  2. Use the Select button to manually locate the MATLAB system libraries.
  3. Restart the Product for the change to take effect. 
     

    mceclip0.png

     
Step 3

Some versions of MATLAB include newer versions of system libraries than the standard version provided by the OS.  The newer libraries are saved in a private location that only MATLAB can access.  This creates problems for the Matlab script integration, since your Lumerical Product will load the standard version of the system library, while MATLAB will load it's private version of the same library.  This creates a conflict, which stops the script integration from working.

The easiest way to avoid this is to roll back to an older version of MATLAB.

Alternatively, you can try to configure your Lumerical Product to work with your current version of MATLAB. This requires configuring our software to use the newer system libraries provided by MATLAB, so both products load the same version of the libraries.  This can be setup by creating a simple shell file that configures the library paths.  Once this file is created, Lumerical can be started with a command new shell file. 

(shell file for FDTD)

$ sudo cat /opt/lumerical/v232/bin/fdtd-matlab.sh 
(Add the following lines into the file)
    #!/bin/bash
    export LD_LIBRARY_PATH=/opt/MATLAB/<version>/sys/os/glnxa64/
    /opt/lumerical/v232/bin/fdtd-solutions $@
(make the file executable)
$ sudo chmod +x /opt/lumerical/v232/bin/fdtd-matlab.sh

(shell file for MODE)

$ sudo cat /opt/lumerical/v232/bin/mode-matlab.sh 
(Add the following lines into the file)
    #!/bin/bash
    export LD_LIBRARY_PATH=/opt/MATLAB/<version>/sys/os/glnxa64/
    /opt/lumerical/v232/bin/mode-solutions $@
(make the file executable)
$ sudo chmod +x /opt/lumerical/v232/bin/mode-matlab.sh

(shell file for CHARGE / HEAT / FEEM & DGTD)

$ sudo cat /opt/lumerical/v232/bin/device-matlab.sh
(Add the following lines into the file)
    #!/bin/bash
    export LD_LIBRARY_PATH=/opt/MATLAB/<version>/sys/os/glnxa64/
    /opt/lumerical/v232/bin/device $@
(make the file executable)
$ sudo chmod +x /opt/lumerical/v232/bin/device-matlab.sh

(shell file for INTERCONNECT)

$ sudo cat /opt/lumerical/v232/bin/interconnect-matlab.sh 
(Add the following lines into the file)
    #!/bin/bash
    export LD_LIBRARY_PATH=/opt/MATLAB/<version>/sys/os/glnxa64/
    /opt/lumerical/v232/bin/interconnect $@ 
(make the file executable)
$ sudo chmod +x /opt/lumerical/v232/bin/interconnect-matlab.sh

Run Lumerical using the new shell file.

$ /opt/lumerical/v232/bin/interconnect-matlab.sh &
$ /opt/lumerical/v232/bin/device-matlab.sh &
$ /opt/lumerical/v232/bin/mode-matlab.sh &
$ /opt/lumerical/v232/bin/fdtd-matlab.sh &

macOS

Step 1

Your Lumerical Product must be able to locate the MATLAB libraries.  If they are not in the system library path, you must manually specify their location. 

Add Lumerical installation path to your shell.

  1. Open Terminal
  2. Add the Lumerical installation path to your current shell. (i.e. All products added to path)
    export PATH=$PATH:/Applications/Lumerical\ v232.app/Contents/Applications/FDTD\ Solutions.app/Contents/MacOS
    export PATH=$PATH:/Applications/Lumerical\ v232.app/Contents/Applications/MODE\ Solutions.app/Contents/MacOS
    export PATH=$PATH:/Applications/Lumerical\ v232.app/Contents/Applications/DEVICE.app/Contents/MacOS
    export PATH=$PATH:/Applications/Lumerical\ v232.app/Contents/Applications/INTERCONNECT.app/Contents/MacOS
    
  3. Do not close or terminate your current shell/Terminal.
  4. Once you close the current shell/terminal window, you will have to run the above "export" commands again on your new shell/Terminal.
  5. To permanently add PATH to your shell profile, checkout this article
  6. Open and run Lumerical from your current shell/Terminal window.
    The new PATH settings will only work when the application is launched from the Terminal window.
    $  fdtd-solutions &
    $  mode-solutions &
    $  device &
    $  interconnect &
  7. Open the Matlab integration status window from the Help menu from within the product.
  8. Use the select button to manually locate the MATLAB system libraries.
  9. Restart Lumerical for the change to take effect. 

mceclip0.png

Step 2

It may be necessary to create the following symbolic link to the MATLAB executable.

sudo ln –s /Applications/MATLAB_<version>.app/bin/matlab /usr/bin/matlab

The exact command will depend on your MATLAB version and install directory.  The above example command is appropriate for MATLAB 2009B installed in the default location.

Test script integration

  • The MATLAB script integration status can sometimes be reported incorrectly.
  • If the status utility reports inactive even after the above configuration, it is still possible that the integration script functions will work.
  • Try a matlab script command on the script prompt of Lumerical's design environment,
    > matlab("plot(1:10)");

mceclip0.png

MATLAB to Lumerical API integration  

The MATLAB API functions allow Lumerical applications and scripts to be called from MATLAB. The Lumerical install and Matlab API paths need to be added to your system and Matlab paths. 

Notes 

A more convenient way to add the Lumerical install path is in MATLAB's path is to add them to the MATLAB's 'startup.m' file, which runs automatically each time MATLAB starts or add Lumerical's product installation folder into your MATLAB's search path. See your MATLAB documentation for more information.

Windows

Include Lumerical installation in the system and MATLAB paths.

  1. Add the Matlab install path and the Lumerical and Matlab API install paths to your system. See this post for details.   
  2. MATLAB must be configured to know the location of the Lumerical API functions.  The API functions are located in the \api\matlab subdirectory of the Lumerical product installation folder. To manually add this location to the MATLAB path, run the following commands in MATLAB:
    path(path,'C:\Program Files\Lumerical\v232\api\matlab')

Linux 

Include Lumerical installation in the system path.

  1. The Lumerical installation bin directory must be added to the system path.
  2. This is done automatically as part of the product configuration script.
  3. It is necessary to add each Lumerical product to the system path.
  4. Change directory to your home directory
  5. Append your .bash_profile with the Lumerical installation path (default install path shown)
    $ cd ~ 
    $ vi .bash_profile
    
    # add the following at the end of you .bash_profile
    PATH=$PATH:/opt/lumerical/v232/bin
    export PATH

Include Lumerical installation in MATLAB path

  1. MATLAB must be configured to know the location of the Lumerical API functions.
  2. The API functions are located in the /api/matlab subdirectory of the Lumerical installation folder.
  3. Manually add this path to the MATLAB path,
    path(path,'/opt/lumerical/v232/api/matlab')

macOS

Include Lumerical installation in system path

Important:

  • Run MATLAB from Terminal. 
  • The API does not work when Matlab is run from Launchpad or Finder using the Icon.
  1. Add the Lumerical installation path to your shell (as shown above)
  2. Run 'matlab' from your current Terminal window
$ /Applications/MATLAB_<version>.app/bin/matlab 

Include Lumerical installation in MATLAB path 

  1. Open the MATLAB application and add the Lumerical MATLAB API file location to the MATLAB path,
    path(path,'/Applications/Lumerical v232.app/Contents/API/Matlab')

Test API functions

In MATLAB run the following,
  1. Confirm that the Lumerical installation directory is included in the system path as seen by MATLAB
    !echo $PATH
  2. Confirm that the Lumerical installation directory is included in the MATLAB path,
    path
  3. Use the MATLAB 'appopen' function to start Lumerical (e.g. FDTD),
    appopen('fdtd')

MATLAB API 

The API allows you to control Lumerical's software from within the MATLAB environment.  Learn more about the API in this  grating coupler optimization  example.

Grating coupler - Matlab-driven optimization (2D)

FDTD Gratings Photonic Integrated Circuits - Passive

In this example, we will demonstrate how MATLAB can be used to drive a multi-variable nonlinear optimization of a grating coupler in FDTD via Lumerical's Automation API. In addition, we will demonstrate how to setup a MATLAB function based on arbitrary simulation parameters to specify a nonlinear constraint for the optimization.

While we focus on a specific example of a grating coupler in FDTD, the target audience includes anyone who is interested in driving and controlling Lumerical applications directly from MATLAB.

Requirements

MATLAB with Optimization Toolbox

MATLAB API Setup and Workflow

The key component required to drive simulations from MATLAB is the automation API that comes with 2016B or newer versions of Lumerical products. To allow for correct functionality, OS must know the location of Lumerical applications. On Windows machines this setup is executed automatically during the installation process, but it might be necessary for Linux users to add the install directory of given Lumerical product to their system path as described on this page.

The second step required for smooth functionality involves telling MATLAB where to look for the API before using any interoperability related commands. The MATLAB API is located in the Lumerical installation folder. In our example when we use FDTD on a Windows machine this would be typically under the following location:

C:\Program Files\Lumerical\FDTD\api\matlab 

One option is to run the following command every time after MATLAB is launched and prior to using API related commands:

path(path,'C:\Program Files\Lumerical\FDTD\api\matlab'); 

The other, more convenient option is to add the path permanently to the startup.m file that is loaded every time MATLAB is launched.

Once the MATLAB API setup is completed we can use the related interoperability commands referenced in the "See Also" section. The basic API workflow is depicted in figure 1 and it consists of four operations:

  1. Open one or more Lumerical session
  2. Send and execute Lumerical script commands to one of the active sessions
  3. Transfer variables between the Lumerical and the MATLAB workspace via an active session
  4. Close Lumerical session

Note that operations 2,3 and 4 can be executed only by referencing to an active session otherwise they will result in an error. The session referencing is done by using an unique ID that is assigned to each session during its initiation. This ID system allows the users to open and control multiple sessions at the same time.

Optimization Project Goal

For this optimization project we use the FDTD simulation file from the Grating Coupler 2D-FDTD example referenced above. This will allow us to compare the results from the MATLAB optimization with the results obtained by using a combination of Lumerical's built-in parameter sweep and particle swarm optimization utility. The goal of the optimization is to maximize the average transmission into the SOI waveguide mode in the wavelength range of 1500nm to 1600nm.

For this example, the following four parameters are chosen as the optimization variables:

  • Angle theta representing the source injection angle in respect to y axis
  • Source position in respect to the grating in x direction
  • Grating pitch
  • Grating duty cycle

In addition, this example demonstrates how to use a nonlinear constraint function that requires a specific FDTD simulation parameter as an input in addition to the variables used for optimization. To do this, we will constrain the x position of the source (xs) so the beam axis at the surface of the grating does not extend beyond the end of the grating itself (x0). This cannot be handled by a simple boundary condition since both angle theta and x position of the source are changing during the optimization. Moreover, we will use the MATLAB API to obtain the information about the distance between the source and the surface of the grating, both being inputs to the constraint function as follows:

xs≥tan(θ)×gap

Figure 3: Visualization of the nonlinear constraint related to the source position and angle theta.

Optimization Project Setup

This project takes advantage of MATLAB "fmincon" multivariable nonlinear constrained optimization algorithm and it consists of four files:

grating_coupler_2D_MATLAB_Optimization.fsp

2D FDTD simulation file. This file is launched from the main MATLAB script via automation API and it returns the average transmission as a function of the input parameters provided by the optimization script

Coupler_Optimization_Main_Script.m

Main MATLAB script file used to:

  • Open, control and close Lumerical client session
  • Specify the optimized function
  • Setup, run and evaluate the optimization
  • Extract simulation parameters for the constraint function

Coupler_Optimization.m

MATLAB function that is called during the optimization. It receives set of parameters from fmincon and sets up the FDTD simulation accordingly. Once the simulation is completed in FDTD, this function extracts the average transmission and passes it back to the optimization routine. Note that since fmincon searches for the global minimum, we specify the figure of merit as fval=1-T_avg;

confun.m

Nonlinear constraint function. Its variables are angle theta, x position of the source and the gap between the source and the grating as shown on figure 3.

To run the example, download all three MATLAB files and the FDTD simulation file into the same folder. Open Coupler_Optimization_Main_Script.m and modify the sim_file_path to the path for the folder containing all downloaded simulation files to specify the location of the FDTD simulation file. Once the path is updated, simply run the simulation file and wait until MATLAB runs multiple optimization iterations. The final values of the optimized parameters and average transmission will be displayed in the MATLAB command window. The MATLAB script files are commented for clarity and can be reviewed in the section below:

Note:

Prior running the example, you need to update the main script for sim_file_path to reflect your folder structure

Coupler_Optimization_Main_Script.m

clear;
%Add Lumerical Matlab API path
path(path,'C:\Program Files\Lumerical\2019b\api\matlab');
sim_file_path=('Change\This\To\Your\Folder\Structure'); % update this path to user's folder
sim_file_name=('grating_coupler_2D_Matlab_Optimization.fsp');
 
%Open FDTD session
h=appopen('fdtd');
%Pass the path variables to FDTD
appputvar(h,'sim_file_path',sim_file_path);
appputvar(h,'sim_file_name',sim_file_name);
 
%Load the FDTD simulation file and get simulation parameters
code=strcat('cd(sim_file_path);',...
    'load(sim_file_name);',...
    'select("grating_coupler_2D");',...
    'coupler_y_pos=get("y");',...
    'coupler_thickness=get("h total");',...
    'select("fiber::source");',...
    'source_y_pos=get("y");',...
    'select("fiber");',...
    'fiber_y_pos=get("y");',...
    'gap=abs(fiber_y_pos+source_y_pos-coupler_y_pos-coupler_thickness);',...
    'select("FDTD");',...
    'FDTD_span=get("x span");');
%send the script in 'code' to Lumerical FDTD
appevalscript(h,code);
 
%Get variables 'FDTD_span' and 'gap' from FDTD workspace to Matlab
%workspace
global gap
gap=appgetvar(h,'gap');
FDTD_span=appgetvar(h,'FDTD_span');
 
 
%Function to be optimized x(x_position,theta,pitch,dc)
f=@(x,y)Coupler_Optimization(x(1),x(2),x(3),x(4),h);
 
%Optimization starting points, constraints and boundaries 
%The format is [x_position in um/10, theta in degrees/10, pitch in  um, duty cycle]
x0=[0.5,1.7,0.75,0.75];
A=[];
b=[];
Aeq = [];
beq=[];
lb=[0,1.1,0.5,0.5];
ub=[FDTD_span/2e-5,2,0.8,0.8];
nonlcon=@confun;
 
%Optimization settings
options = optimoptions('fmincon');
options = optimoptions(options,'FiniteDifferenceStepSize',1e-3);
options = optimoptions(options,'Algorithm','sqp');  %alt: interior-point
options = optimoptions(options,'MaxIter', 100);
options = optimoptions(options,'PlotFcns', { @optimplotfval });
options = optimoptions(options,'Display','iter-detailed');
options = optimoptions(options,'StepTolerance',1e-3);
 
%Run optimization
[x,fval]=fmincon(f,x0,A,b,Aeq,beq,lb,ub,nonlcon,options);
T_avg=1-fval;
 
%Display optimization results
disp(strcat({'Optimized x position: '},num2str(x(1)*10),{' um'}));
disp(strcat({'Optimized angle theta: '},num2str(x(2)*10),{' degrees'}));
disp(strcat({'Optimized pitch: '},num2str(x(3)),{' um'}));
disp(strcat({'Optimized Duty cycle: '},num2str(x(4))));
disp(strcat({'Optimized T_avg: '},num2str(T_avg)));
 
%Close session
appclose(h);

Coupler_Optimization.m

function y=Coupler_Optimization(x_position,theta,pitch,dc,h)
 
%Modify fiber position, theta, duty cycle, pitch and run the
%simulation
code=strcat('switchtolayout;',...
'select("grating_coupler_2D");',...
'set("pitch",',num2str(pitch*1e-6,16),');',...
'set("duty cycle",',num2str(dc,16),');',...
'select("fiber");',...
'set("x",',num2str(x_position*1e-5,16),');',...
'set("theta0",',num2str(theta*10,16),');',...
'run;');
appevalscript(h,code);
 
%Get the coupled power from T monitor to
%FDTD workspace as variable 'T_avg_FDTD'
code=strcat('T_avg_FDTD=getresult("model","T_avg");');
appevalscript(h,code);
 
%Get the average transmission(figure of merit) from FDTD workspace to
%MATLAB workspace
T_MATLABFun=appgetvar(h,'T_avg_FDTD');
y=1-abs(T_MATLABFun);
 
%Uncommnet this section to display the optimized parameters and
%figure of merit for each run in FDTD
%disp(strcat('x_pos= ',num2str(x_position,10),'...theta= ',num2str(theta,10),'...pitch= ',num2str(pitch,10),'...DC= ',num2str(dc,10)));
%disp(strcat('1-abs(T)= ',num2str(y,10)));
end

confun.m

function [c, ceq] = confun(x)
 
% Nonlinear inequality constraints x(x_pos,theta,pitch,dc)
global gap
c = tan(x(2)*pi/180)*gap-x(1)*1e-5;
 
% Nonlinear equality constraints is left empty
ceq = [];

Optimization Results

The maximum average transmission achieved with the MATLAB driven optimization is ~40%, which is in good agreement with the value obtained using the Lumerical built-in parameter sweep/particle swarm optimization routines. The optimized values for all parameters shown in table 1 are close to the reference example demonstrating that we are able to reliably find the optimal parameters using this methodology. Note that the exact values might slightly change in each optimization run as the function minimum can be achieved with a range of parameter values rather than with one exact set of values.

Parameter

MATLAB optimization value

Reference example value

Theta [degrees]

12.21

13.45 (fixed)

Source x position [um]

3.15

3 um (from parameter sweep)

Pitch [um]

0.6475

0.66

Duty Cycle

0.67

0.66

Optimized average transmission

0.394

0.388

Table 1: Comparison between the optimized parameters and the reference example

The time required for the four-variable optimization is comparable to the time required for the two-variable optimization with the particle swarm method, and it can be considerably influenced by setting the starting points, boundaries and the optimization parameters. Figure 4 shows comparison of two identical optimization setups that differ only in the finite difference step size (FDSS). It is clear that smaller step takes longer to estimate the trends and close in on the optimal values. As a result, we were able to achieve the optimized transmission within 8 iterations with FDSS=1e-3, while 14 iterations were required with FDSS=1e-4.

 

Figure 4: Tracking of the figure of merit(fval=1-Average Transmission) for different finite difference step size (left shows 1e-3 and right shows 1e-4)

Optimization tips

  • If the finite difference step size is too small, the simulation result might not change significantly and the optimization algorithm might terminate prematurely. For example, in our 2D FDTD simulation, moving the source by 1nm in x direction will have minimal to no impact on the resulting average transmission.
  • It is a good idea to run the optimization multiple times with slightly different starting points and boundaries to verify that the results are comparable.
  • If the optimization ends with one or more parameters having the boundary value, it is likely that the minimum is artificial and the boundary should be moved.
  • Sometimes it can be useful to have the optimization parameters within the same order of magnitude.

 Read/Write .mat files

Lumerical can  save  and  load  data to the commonly used .mat file format, making it easy to do post processing with MATLAB. 

matlabsave - Script command

FDTD MODE DGTD CHARGE HEAT FEEM INTERCONNECT

Save Lumerical workspace variables to MATLAB .mat data files.

Syntax

Description

matlabsave("");

Save all workspace variables to a .mat file that has the same name as the simulation file.

This function does not return any data.

matlabsave("filename");

Saves all workspace variables to the specified .mat file.

matlabsave("filename", var1, ..., varN);

Saves the specified workspace variables to the .mat file.

Examples

Simple example:

x=1:10;
y=x^2;
matlabsave("x_squared_data", x, y);

Save data from a monitor named xy_monitor. The data is first obtained with script functions such as getdata and transmission. These workspace variables are then saved with the matlabsave function. Note that complex file names can be created with the num2str command. This is useful when doing parameter sweeps where a unique file name is required for each point in the sweep.

# get raw matrix data from the simulation
mname="xy_monitor";       # monitor name
x=getdata(mname,"x");      # position vectors associated with Ex fields
y=getdata(mname,"y");      # position vectors associated with Ex fields
Ex=getdata(mname,"Ex");     # Ex fields at monitor
T=transmission(mname);     # Power transmission through monitor
 
# save matrix variables x, y, Ex, T and i to a data file
i=1;
filename="results_"+num2str(i); # set filename. i could be a loop counter variable.
matlabsave(filename, x,y,Ex,T,i); 

Save a Lumerical dataset (eg. Electric field vs x,y,z,f) to a .mat file. Lumerical datasets will be imported into Matlab using the struct data type.

# get electric field dataset from the simulation
mname="xy_monitor";       # monitor name
E=getresult(mname,"E");     # E fields at monitor
 
# save dataset to mat file
filename="ElectricField";
matlabsave(filename, E); 

 

matlabload - Script command

FDTD MODE DGTD CHARGE HEAT FEEM INTERCONNECT

Load Matlab .mat data into workspace

Syntax

Description

matlabload("filename");

Load to the workspace the data of the specified .mat file.

Examples

This is a simple example that shows how to load to workspace from a .mat data file.

#this file has variables data1, data2, data3
matlabload("myData.mat");  
?workspace;
matrices:
 data1 data2 data3

Export figure to MATLAB 

 Line and surface plots within Lumerical can easily be exported to MATLAB. See the MATLAB export section of Using the data visualizer and figure windows.

Using the data visualizer and figure windows

FDTD MODE DGTD CHARGE HEAT FEEM INTERCONNECT

mceclip0.png

This page explains how to use the data visualizer and figure windows to view your simulation data. 

Introduction

Simulation results can be visualized using 1D lines, a 2D surface, and 3D plots. These plots can be created from within the results visualizer ("plot in new window" button), or from a script. 

Plot windows support standard operations such as axis labels, zoom, export to JPG, etc. Pressing the left mouse button to zoom in by a factor of two, the right button to zoom out by a factor of two, pressing and holding the left-hand mouse button results in a zoom window, and double-clicking either mouse button scales the plot to show all of the data. Some controls are slightly different for each type of plot (see more details in the next sections). For example, only the 3D vector plot provides controls for 3D rotation of the view; SHIFT key + mouse LEFT click allows pan view without 3D rotation. For image plots, the colormap scale can be changed from color to grey, or red2blue.

The FILE menu contains an option to export the current figure to a JPG image file.

The SETTINGS menu contains options for setting the axes, colorbar limits, color map, labels, etc.

Visualizing rectilinear data

In this section, we describe the visualizer tools for data structured in a rectilinear grid (eg. FDTD simulation results).

Available plot types

Line (xy plot): Choose this option to plot a 1D vector versus another 1D vector. For matrices with more than 1 dimension, a slice of the matrix will be automatically chosen. You can use the parameters table on the bottom to choose which dimension to slice and which to plot on the x- or y-axis, e.g., a spectrum (field amplitude vs. wavelength)

line_plot_example.jpg

Line (Smith chart): Use this option for plotting impedance data. For more information see Wikipedia. (Example:  Microstrip with a lumped RLC element) 

smith_chart_explained.png

Line (Polar plot): Choose this option to plot the angular distribution of some quantity. The angular coordinate is in degrees. The data must be provided as a function of the angle in radians. (Example:  Mie scattering 3D)

polar_plot_example.jpg

Image: Choose this option to create a 2D image plot of monitor data. For matrices with more than 2 dimensions, slices of the matrix will automatically be chosen. You can use the parameters table on the bottom to choose which dimensions to slice and which to plot on the x or y-axis, e.g., a spatial field profile (field vs. x,y), slice wavelength.

surface_plot_example.jpg

Vector: Choose this option to create a 2D/3D vector plot of monitor data. Choose the parameters table to slice a frequency point. It is possible to create a vector plot of quantities such as the electric field, magnetic field, Poynting vector, etc.

Note:

  • It is often more meaningful to plot the Poynting vector rather than the fields. Plots of the electric field will often contain vectors pointing in different directions representing the oscillation of the field direction. The more interesting quantity to plot is the Poynting vector to visualize the direction of power flow.
  • It can be helpful to create an electric field vector plot to study circularly polarized or elliptically polarized beams. See  the circular polarization example.

vector_plot_example.jpg

Features

icon_plot_in_matlab_menu.png

icon_export_to_matlab.png

MATLAB export / MATLAB export script: Only available for line-xy and surface plots. These buttons generate a MATLAB plot using the data plotted in the Visualizer; In addition, the MATLAB export script button creates a script that generates the plot in MATLAB. It requires MATLAB integration. To switch between these two buttons click and hold the button until you see the two options as shown below:

MATLAB_export.png

icon_JPG_plot.png

Export to JPG: It exports the figure to a JPG file. For line plots it is possible to export to PDF and EPS files as well. Click and hold the button to see the available options as shown below:

jpg_export.png

COPY_TO_CLIPBOARD.PNG

Copy to clipboard: It copies the image to clipboard. 

COPY_TO_CLIPBOARD2.PNG

alt

 Show/hide chart settings: Opens the Visualizer settings described in the next section.

icon_plot_help.png

Get help with graph control options: Available for vector plots only. Shows a description of the control options to zoom in/out, rotate, pan, spin, switch between wireframe and solid view, and reset the camera.

Smith chart additional options:

  • ASPECT RATIO: Choose between 1:1 and fill the scene.
  • NORMALIZING IMPEDANCE (OHMS): Set the characteristic impedance of the system used for normalization.

Vector plots additional options: Choose to downsample the data, scale vectors by a given factor, show data points, invert background color, apply illumination, and use parallel projection.

visualizer_settings_surface_plot.PNG

visualizer_settings_vector_plot.PNG

Plot data redraw options: There are two options:

  • Hold plot settings: When enabled, the current settings (e.g. color bar limits) are applied to any data set (or a slice of it) plotted in the visualizer.
  • Auto redraw: When enabled, the plot is refreshed automatically after any change in the settings or data set selection. If the option is disabled, it is necessary to click on the Redraw button to update the plot; this is particularly useful when visualizing large data sets. 

Phase shift animation: Visualize a continuous wave response of the field by changing the phase of the propagating field. Works only for scaler data or one of the components (X, Y, Z) of vector data.

  • frames per cycle: set number of frames per cycle.
  • FPS: set number of frames per second.
  • Export: export field with phase changes as a movie.

mceclip0.png

Export to: Export figure to JPEG, text file or clipboard 

Overplot Lines

This option is used to plot a series of lines with different indices from a 2D image plot in a 1D line plot. This is useful to give a clear comparison of the results with respect to different parameter values. To overplot lines:

  1. Change the "Plot Type" from "Image" to "Line"
  2. Select the index parameter "Action" to be "Slice"
  3. Turn on the "Overplot Lines" radio button 
  4. Key in the indices for the lines, separated with a comma

mceclip5.png

Visualizing unstructured data

The visualizer for unstructured data is very similar to the one for rectilinear data described in the previous section. However, for unstructured data the only plot type available is surface and some toolbar buttons are not available. In addition, the visualizer settings are significantly different as described next.

visualizer_unstructured_snapshot.PNG

Some of the visualizer settings are common to 2D and 3D simulation data. These are:

  • SHOW: Can be "surface", which will contain the values at each mesh point only, or "surface and mesh", which will superimpose in black the mesh grids on top of the plots, or "mesh only" which will only plot the mesh grid in color.
  • AXIS SCALE OPTIONS: Can be "square" which will make sure the two axis are plotted to the same size, or "equal" which will use the same scale for both such that the plot will be to scale.
  • LOG SCALE: Will plot the result on a log scale.
  • TITLE: The title of the plot can be specified.
  • X/Y/Z LABEL: The x, y, and z labels for the plot can be specified.
  • COLOR BAR: The color bar limits can be specified and locked. Additionally, it is possible to use a background and border for the color bar.

The specific options for 1D, 2D, and 3D data are described below.

Options for 1D data

1D data captured by line monitors in solvers based on the finite element method can follow a curved path. To express the recorded data in a comprehensive way, the position on the curve is shown as value s normalized to the total length of the curve. Hence, the resulting plot shows the variable of our interest as a function of parameter s that has values between 0 and 1 representing the start and the end of the monitor curve.

The position of the start and end points s=0 and s=1 for closed curves are arbitrarily determined as a unique point with minimal in x, then minimal in y, then minimal in z.

Note: The exact x,y,z coordinates corresponding to each E field/s data point are available in the monitor results.

1D_line_plot.png

Options for 2D data

It is possible to choose between two plot types: surface and image. In the 2D image plot, the values are indicated using the color bar. In the surface plot, the values are also plotted in the third dimension. For a surface plot, it is possible to plot data as a radiation plot which will plot data in spherical coordinates and the distance of each data point from the origin will determine it's value or intensity. This is specifically useful in the case of far-field projections or a similar type of data where the intensity of data points at each direction in a 3D space is of interest.

surface_plot_unstructured.jpg

image_plot_unstructured.jpg

Surface (xyz plot) and Image plot of the same data

gaussian_image_plot.jpg

gaussian_radiation_plot.jpg

Image plot and Radiation plot of the same Gaussian beam

Options for 3D data

  • DATA VISUALIZATION: Choose between three options: unclipped (default), clipped volume, and clipped plane. When a clipping option is selected a clip plane cuts through the 3D structure and gives insight into the inside of the 3D plot.
  • CLIP PLANE: The clip plane can be shown on top of a 3D surface plot. This plane is defined by the coordinates of the origin and components of a vector perpendicular to the plane. For convenience, there are also the quick options for choosing an x-normal / y-normal / z-normal plane. The inside out option will flip on which side of the plane is shown. To change the plane position and/or orientation, move the arrow perpendicular to the plane, grabbing it with a mouse left-click much like a drag action. For Pan view, hold the keyboard SHIFT key and mouse left click.

clipped_volume_unstructured.png

clipped_plane_unstructured.png

Clipped volume and Clipped plane

  • 2D PLANE DATA: Use this option to export the cross-section 2D data at the clip plane to the script workspace or to show it in a new Visualizer window.

Understanding the Attribute editor

When using line plots, each attribute will appear as a separate line. When using image and vector plots, the selected attribute will be shown.

ref_MODE_analysis_visualizer_attributes.png

DATA SET: full data set name (can contain multiple attributes)

  • ATTRIBUTE: attribute name
  • VECTOR OPERATION: selects a particular component of a vector attribute e.g. (Ex, Ey, |E|^2)
  • SCALAR OPERATION: selects a particular component of a scalar attribute e.g. (real, imag, abs, angle)
  • SCALE: multiplier for the data being plotted
  • LEGEND: this name will be shown in the legend of the plot
  • NOTES: additional information added by the user about the attribute
  • VIEW DATA: allows users to view the data in a table format as shown below

ref_viewdata.png

In this table format, users can select any portion of the data and "Copy" or "Export" it into a text file. Alternatively, users can also send any portion of the data into the Script Workspace.

Understanding the Parameter window

  • ATTRIBUTES: Name of the associated attribute
  • PARAMETERS: Name of the parameter
  • ACTION: Control how the parameter is treated in the plot. For example, select which axis to plot the parameter on.
  • VALUE: displays the value if it is a singular value or is blank if there is a vector of values

ref_MODE_analysis_visualizer_parameters.png

Plotting multi-dimensional attributes

Line plots

One parameter must be selected to plot on the x-axis. All other non-singleton parameters must be set to Slice. A specific slice can then be selected for those parameters.

Surface plots

Two parameters must be selected to plot on the x- and y-axis. All other non-singleton parameters must be set to Slice. A specific slice can then be selected for those parameters.

Vector plots

The spatial dimensions (x,y,z) are always selected to plot on the x-, y-, z-axes. All non-spatial parameters must be set to Slice. A specific slice can then be selected for those parameters.

See also 

The following pages provide useful tips for visualizing Lumerical data with MATLAB. 

Creating 2D image plots with MATLAB

usr_matlab_contour.jpg

This page shows how to create 2D image plots of data from Lumerical's software using MATLAB.

MATLAB uses a different convention for plotting 2D matrix data than Lumerical. To get the same figure orientation in MATLAB as in your Lumerical plots, you must apply an unconjugated transpose operation and adjust the axes, as shown below.

2D image plot with uniform, rectilinear data

Lumerical image plot

x = 1:3;
y = 1:4;
A = [1,2,3,4;5,6,7,8;9,10,11,12];
matlabsave("toPlot.mat",x,y,A);
image(x,y,A);

MATLAB commands to generate equivalent plot

load('toPlot.mat');
% transpose matrix, plot data, add color bar
A2 = A.';      
imagesc(x,y,A2);  
colorbar;
% set axis limits      
set(gca,'Xlim',[min(x),max(x)]); 
set(gca,'Ylim',[min(y),max(y)]); 
% set Y axis direction
set(gca,'YDir','normal');     

2D image plot with non-uniform, rectilinear data

The standard image command in MATLAB assumes that matrix data is uniformly sampled, even when you provide the x,y position vectors. This is not true of the image command in the Lumerical script environment. This is an important detail when plotting data obtained from a non-uniform mesh. In the following example, notice that the Gaussian profile is not sampled uniformly in the Y direction. To plot this data in Matlab, you must interpolate the data on a uniform grid, as shown below.

Lumerical image plot

x = linspace(-1.5,0.5,100);
y = [linspace(-2,0,20); linspace(0.01,1,100)];
X = meshgridx(x,y);
Y = meshgridy(x,y);
A = exp(-(1+3*X)^2-(0.5+Y)^2);
 
matlabsave("toPlot.mat",x,y,A);
image(x,y,A);

MATLAB commands to generate equivalent plot

load('toPlot.mat');
% create linearly spaced vectors
x2 = linspace(min(x),max(x),200); 
y2 = linspace(min(y),max(y),200);
% create 2D mesh grids. Note that X,y vectors are reversed, 
% as required by Matlab's different plotting convention
[X,Y]  = meshgrid(y,x);      
[X2,Y2] = meshgrid(y2,x2);
% interpolate to new vectors     
A2 = interp2(X,Y,A,X2,Y2);  
% transpose matrix
A3 = A2.';
% plot data, add color bar, set axis limits, set Y axis direction     
imagesc(x2,y2,A3); 
colorbar;      
set(gca,'Xlim',[min(x),max(x)]); 
set(gca,'Ylim',[min(y),max(y)]); 
set(gca,'YDir','normal');

Alternatively:

load('toPlot.mat');
A2=A.';
pcolor(x,y,A2);
colorbar;
shading interp;

 

Creating vector plots with MATLAB

This page shows how to create a vector plot of rectilinear data from Lumerical's software using MATLAB.

MATLAB uses a different convention for plotting matrix data than Lumerical. To get the same figure orientation in MATLAB as in your Lumerical plots, you will need to define a uniform grid for the spatial vectors, x, y, z. This can be done in MATLAB or in Lumerical's scripting environment; however, since MATLAB's convention for creating meshgrids is different from Lumerical's convention, it is a lot easier to do this in Lumerical's scripting environment before exporting the data to MATLAB. Let us assume we have the fields from a monitor named "monitor" in FDTD:

FDTD post processing step

# Get field and position vectors Ex=getdata("monitor","Ex"); Ey=getdata("monitor","Ey"); Ez=getdata("monitor","Ez"); x=getdata("monitor","x"); y=getdata("monitor","y"); z=getdata("monitor","z"); # Choose a frequency point ( the first one ) Ex=pinch(Ex,4,1); Ey=pinch(Ey,4,1); Ez=pinch(Ez,4,1); # Specify the resolution of the plot  res_x=10; res_y=10; res_z=3; # Define uniform vectors x2=linspace(x(1),x(length(x)),res_x); y2=linspace(y(1),y(length(y)),res_y); z2=linspace(z(1),z(length(z)),res_z);  xmesh = meshgrid3dx(x2,y2,z2); ymesh = meshgrid3dy(x2,y2,z2); zmesh = meshgrid3dz(x2,y2,z2); # Interpolate fields on new uniform vectors Ex=interp(Ex, x, y, z, x2, y2, z2); Ey=interp(Ey, x, y, z, x2, y2, z2); Ez=interp(Ez, x, y, z, x2, y2, z2); matlabsave("monitor_data",Ex,Ey,Ez,xmesh,ymesh,zmesh);

Once the 3d uniform grids have been created, we can either plot them in Lumerical's scripting environment or load the data file in MATLAB and plot them in MATLAB.

Lumerical script to generate vector plot

E = rectilineardataset("E",x2,y2,z2); E.addattribute("E",Ex,Ey,Ez); vectorplot(E);

MATLAB script to generate same plot

load('monitor_data.mat');quiver3(xmesh*1e6,ymesh*1e6,zmesh*1e6,real(Ex),real(Ey),real(Ez));xlabel('x');ylabel('y');zlabel('z');

Creating 3D visualizations with MATLAB

This example shows how to visualize 3D data from Lumerical FDTD in MATLAB.

The MATLAB function scatter3() allows visualization of data, in this case, E-field values, at points in 3D space. In this example, a single frequency Gaussian beam is focused in free space and the area around the focal point is imaged. Occlusion is a major problem for such plots, thus, we threshold the number points that are displayed, focusing only on the volume of interest. In the resulting figure, we can clearly see the focal point of the Gaussian beam.

First, download and run the simulation usr_matlab_simple_beam.fsp . Since there are no structures, the simulation should run fairly quickly. Next, run the script usr_script_3d_scatter.lsf . It picks out points over the specified threshold value and writes them to e_field.txt .

m_name = "monitor2";
thresh = 1.3;   # set threshold, fields above this value will be shown
mon=pinch(getelectric(m_name),4,1); # picks the first freq
xmon=getdata(m_name,"x");
ymon=getdata(m_name,"y");
zmon=getdata(m_name,"z");
n=size(xmon);
n=n(1);
# setup empty arrays
s=sum(monthresh);
x=matrix(1,s);
y=matrix(1,s);
z=matrix(1,s);
ef=matrix(1,s);
# get positions of (x,y,z) over threshold value
t=1; #counter
for(i=1:n) {
 for(j=1:n) {
  for(k=1:n) {
   if(abs(mon(i,j,k))thresh) {
     x(t)=xmon(i);
     y(t)=ymon(j);
     z(t)=zmon(k);
     ef(t)=abs(mon(i,j,k));
     t=t+1;
   } 
  } 
 } 
}
# write data to a txt file to be imported into Matlab
f="e_field.txt";
del(f);
write(f,num2str(x));
write(f,num2str(y));
write(f,num2str(z));
write(f,num2str(ef));

Next, open up Matlab and set the working directory to where e_field.txt was saved. Running the following code, contained within usr_matlab_script_3d_scatter.m will generate the interactive 3D plot seen above. Note that the axis limits should be set to the same values for a correct spatial representation. The image above is stretched out in the x and y directions whereas in reality, the beam is spatially more narrow.

% simple matlab script that plots single frequency 3D monitor data
e_field=dlmread('e_field.txt','\t'); % tab delimited
a=e_field(1,:); % x
b=e_field(2,:); % y
c=e_field(3,:); % z
e=e_field(4,:); % e-field value
size=25;     % rendering size of plotted points 
% plot the data and label
scatter3(a*1e6,b*1e6,c*1e6,size,e);
xlabel('x-axis (um)');
ylabel('y-axis (um)');
zlabel('z-axis (um)');
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值