Tips and tricks when using the ZOS-API with MATLAB

This article provides some helpful tricks and tips in MATLAB to enhance your productivity and fully utilize the capability of the ZOS-API.

Authored By Alastair Humphrey


Article Attachments


In OpticStudio there exists an application programming interface (API) that allows the user to connect and interact with different scripting environments. With API users may communicate with open instances of OpticStudio (Interactive Extension) or run OpticStudio in the background (Standalone Application). This is particularly useful for repetitive calculations or if the user wants to manipulate the data produced by OpticStudio. In this article, only ZOS-API in conjunction with MATLAB will be discussed, and certain tips and tricks will be highlighted.


In MATLAB, it is possible to use Intellisense for code completion (left) or to list the members (right):



This is particularly useful to increase the speed of the coding process by reducing typos and other common mistakes. However, when the MATLAB script has completed, it is not possible to access what is inside the variables. For example, we can run a section of the sample file Example 01: New File and QuickFocus included with the OpticStudio installation to check. If we want to access the TheLDE and the MATLAB script has already terminated, we would be issued with the message, ‘No completions found.’:



To avoid this issue, we must a run a MATLAB script and insert a breakpoint to stop the script from ending. This is applicable when using the Standalone Application or when you have placed your code within the MATLABZOSConnection script for the Interactive Extension. A breakpoint may be inserted by navigating to Editor…Breakpoints…Breakpoints…Set/Clear in MATLAB:



A breakpoint is indicated by a red circle next to the row number in MATLAB. In this case, we have entered a breakpoint at row 44:



We can now use Intellisense in either the Script Editor or Command Window in MATLAB by pressing the TAB key after a period (.):




Alternatively, instead of placing our code within the MATLABZOSConnection script for the Interactive Extension, which was generated in OpticStudio, we can place our code in a separate script, add the path to the MATLABZOSConnection script and define TheApplication as the same MATLABZOSConnection. In this case, the connection number is 21. Below is an example of code that could be used:


addpath('\\zmefs01\redirectedfolders\alastair.humphrey\Documents\Zemax\ZOS-API Projects\MATLABZOSConnection21\')

TheApplication = MATLABZOSConnection21;


With either of the above methods. API commands can be tested with OpticStudio, and we can observe the results of the commands in real time. Also, the command window can be used as a useful debugging tool. Because the main function hasn’t ended in both cases, we can still investigate our declared objects by clicking any object in the workspace:



Using .NET methods with an ‘out’ parameter

Below is an example of using .NET methods with an ‘out’ parameter with GetIndex:



When using .NET methods which have an ‘out’ parameter in MATLAB, you must be careful to make sure that the object you feed the method to is of the correct type. In this case, we need a double array, whose length is equal to the number of wavelengths.  The following code is an example where the index for Surface 2 for each of the three wavelengths is returned:


surf_num = 2;

num_waves = 3; % probably shouldn't hard code this

index = NET.createArray('System.Double', 3);

TheApplication.PrimarySystem.LDE.GetIndex(surf_num, num_waves, index);

index_data = index.double;


MATLAB function methods and methodsview

The MATLAB functions methods and methodsview may be used to view the class method names. For example, we may write:




to obtain:



Reading enumerations in MATLAB

Occasionally in OpticStudio, we may want to loop through the enumerations in MATLAB to read data in. For example, we may want to read in the coefficients from the Even Asphere surface into MATLAB.

The surface sag of the Even Asphere Surface is given by:



We can use the Even Asphere sample file "{Zemax}\Samples\Sequential\Objectives\Even Asphere.zmx" as an example and read in the coefficients:



One such way to read the data into MATLAB is to use the eval function and loop through the enumeration:


TheSystem = TheApplication.PrimarySystem;

TheLDE = TheSystem.LDE;

for no_coeff=1:8

EA_coeff(no_coeff) = eval(['TheLDE.GetSurfaceAt(2).GetSurfaceCell(ZOSAPI.Editors.LDE.SurfaceColumn.Par' num2str(no_coeff) ').DoubleValue']);




Performance timing functions in MATLAB

There are useful time functions in MATLAB which have the capability to estimate how long your code or a portion of your code takes to run. These functions may useful to check optimization or tolerancing times when using ZOS-API.

  • One way is to use the timeit function, which will run a function multiple times and return the median of the time taken for execution.
  • A second way is to use the profile function, which will return statistics of the execution time of a particular function.
  • Alternatively, the stopwatch timer functions can be used. The stopwatch timer functions will now be discussed. The tic function starts the stopwatch and toc stops the stopwatch:


The code below is an extract of the sample code "{Zemax}\ZOS-API Sample Code\MATLAB\MATLABStandalone_15_Seq_Optimization.m"



TheMFE = TheSystem.MFE;

OptWizard = TheMFE.SEQOptimizationWizard;

%Optimize for smallest RMS Spot, which is "Data" = 1

OptWizard.Data = 1;

OptWizard.OverallWeight = 1;

%Gaussian Quadrature with 3 rings (refers to index number = 2)

OptWizard.Ring = 2;

%Set air & glass boundaries

OptWizard.IsGlassUsed = true;

OptWizard.GlassMin = 3.0;

OptWizard.GlassMax = 15.0;

OptWizard.GlassEdge = 3.0;

OptWizard.IsAirUsed = true;

OptWizard.AirMin = 0.5;

OptWizard.AirMax = 1000.0;

OptWizard.AirEdge = 0.5;

%And click OK!





    LocalOpt = TheSystem.Tools.OpenLocalOptimization();

    if ~isempty(LocalOpt)

        LocalOpt.Algorithm = ZOSAPI.Tools.Optimization.OptimizationAlgorithm.DampedLeastSquares;

        LocalOpt.Cycles = ZOSAPI.Tools.Optimization.OptimizationCycles.Automatic;

        LocalOpt.NumberOfCores = 8;

        fprintf('Local Optimization...\n');

        fprintf('Initial Merit Function %6.3f\n', LocalOpt.InitialMeritFunction);


        fprintf('Final Merit Function %6.3f\n', LocalOpt.CurrentMeritFunction);



    % Get the elapsed time as a TimeSpan value.




Local Optimization...

Initial Merit Function  0.363

Final Merit Function  0.170

Elapsed time is 1.765178 seconds.


MATLAB Live Editor

MATLAB Live Editor is a great tool where you can create live scripts, which can show the output in parallel with the code. Additionally, you may add text, equations, images and hyperlinks. More information on the MATLAB Live Editor may be found here.



Below is an example, where the Wavefront Map and FFT MTF of the Cooke Triplet has been retrieved from OpticStudio and plotted as a MATLAB figure. The MLX file (MATLAB live script file format) used for this example is an attachment to this article.



A useful feature of the MATLAB Live editor is the Section Break where it is possible to create sections of code and run them independently.



For example, with the Cooke Triplet we could select the portion of code that calculates the AOI of Chief ray at each surface and click the ‘Section Break’ icon. If we click on the ‘Check AOI of Chief Ray at each Surface’ section (a blue box appears around section) and then click on the ‘Run Section’ icon, we can evaluate that section of code separately.



Was this article helpful?
0 out of 0 found this helpful



Article is closed for comments.