# Understanding the main Interfaces of ZOS-API using MATLAB

This article is a review of the main Interfaces of ZOS-API. It follows the structure of the Help File under The Programming Tab...About the ZOS-API. For each interface, we will mention the associated Help File section and it is recommended to read it. The article will then highlight the important parts and then you will get a chance to practice. The current article is written for MATLAB.

Authored By Julia Zhang and Yihua Hsiao

## Introduction

ZOS-API is built as a hierarchy of Interfaces. Those Interfaces give access to different features of OpticStudio. Let's have a look at the main ones.

## IZOSAPI_Application TheApplication

### Definition

TheApplication is a variable, an object which is an instance of the IZOSAPI_Application Interface.

As defined in the Help File, TheApplication (or whatever you choose to call this variable) is the point of access to all facets of ZOS (Zemax OpticStudio) that have been made available to you. Let’s have a look at TheApplication.

How to use it

To connect to OpticStudio Interactive extension with Matlab, click Programming…MATLAB…Interactive Extension to generate the boilerplate code. In this code, app = TheConnection.ConnectAsExtension(instance) is used to connect to an existing instance of OpticStudio.

To connect to OpticStudio Standalone Application with Matlab, click Programming…MATLAB…Standalone Application to generate the boilerplate code. In this code, app = TheConnection.CreateNewApplication() is used to launch a new instance of OpticStudio in 'headless' mode. Note that although the OpticStudio window is not visible, it still requires an active license.

Here are a few useful commands:

• Close the Application: TheApplication.CloseApplication();
• Check the ‘Edition’ of your license: TheApplication.LicenseStatus;
• Check the ‘Mode’ of your license: TheApplication.Mode;
• Change the language of OpticStudio to English: TheApplication.Preferences.General.Language=ZOSAPI.Preferences.LanguageType.English;
• Get the full path of the Sample Files folder: sampleDir = TheApplication.SamplesDir

## IOpticalSystem PrimarySystem

### Definition

As defined in the Help File, the PrimarySystem property gives us access to the currently loaded .ZMX file and provides several operations and data access.
TheSystem = TheApplication.PrimarySystem;

### How to use it

TheSystem gives access to editors: .LDE for the Lens Data Editor, .MCE for the Multi Configuration Editor, .MFE for the Merit Function Editor, .TDE for the Tolerance Data Editor, .NCE for the Non-Seqential Editor. It also gives access to analysis using .Analyses and tools using .Tools.

Here are some useful operations available from TheSystem:

• Switch to Non-sequential Mode: TheSystem.MakeNonSequential();
• Switch to Sequential Mode: TheSystem.MakeSequential();
• Load a file (.ZMX): testFile = System.String.Concat(sampleDir, '\Sequential\Objectives\Double Gauss 28 degree field.zmx');TheSystem.LoadFile(testFile, false);
• Save the existing system (.ZMX): TheSystem.Save();
• Save the current system to a new file: TheSystem.SaveAs(copyFile);
• Create a new (default) lens data file (LENS.ZMX) : TheSystem.New(false);
• Close the currently open system without saving it: TheSystem.Close(false);

## ISystemData SystemData

### Definition

As defined in the Help File, TheSystemData holds all the basic data of the System. It gives access to the System Explorer settings.
TheSystemData = TheSystem.SystemData;

### How to use it

TheSystemData gives access to properties like Aperture, Fields, Wavelengths, Environment, RayAiming, NonSequentialData, Polarization, ...

Here are some useful operations to change settings in TheSystemData :

• Change a setting in a drop-down menu: a settings in drop-down menus of OpticStudio can only take a predefined list of  values. In ZOS-API, those lists are exposed as enumerations. For example, to change the system aperture type to Entrance Pupil Diameter, select the EntrancePupilDiameter enum which is a member of ZemaxApertureType.
TheSystemData.Aperture.ApertureType=ZOSAPI.SystemData.ZemaxApertureType.EntrancePupilDiameter;
• Change a value setting:
TheSystemData.Aperture.ApertureValue=20;
• Change a string setting: sysTitleNotes = TheSystem.SystemData.TitleNotes;
• Set a coating file and reload it : sysFiles = TheSystem.SystemData.Files; sysFiles.CoatingFile = 'COATING.DAT';TheSystem.SystemData.Files.ReloadFiles();
• Add a title: sysTitleNotes.Title = 'Add here the title';
• Tick or untick a checkbox. True represents the ticked option, False the unticked one: TheSystemData.Aperture.AFocalImageSpace = true;

Here are some useful operations to change the Fields and Wavelengths:

• Access Fields : sysField = TheSystem.SystemData.Fields;
• Access Wavelengths: sysWave= TheSystem.SystemData.Wavelengths;
• Add a new field X = 0, Y = 5.0 and Field weight = 1: NewField_2 = sysField.AddField(0,5.0,1.0);
• Add a new wavelength 0.6328 micron with a weight equal to 1.0: NewWave_2 = sysWave.AddWavelength(0.6328,1.0);
• Change Field 1 values to X = 1.0 and Y = 2.0 and Field weight = 0.5: field1 = sysField.GetField(1); field1.X = 1.0; field1.Y = 2.0; field1.Weight = 0.5;
• Change Wavelength 1 to 0.55 micron : TheSystemData.Wavelengths.GetWavelength(1).Wavelength = 0.55;
• Set Wavelength 1 as the primary wavelength, write : TheSystemData.Wavelengths.GetWavelength(1).MakePrimary();
• Change the Field Type to Object Height: sysField.SetFieldType(ZOSAPI.SystemData.FieldType.ObjectHeight);
• Change Normalization to Radial: sysField.Normalization= ZOSAPI.SystemData.FieldNormalizationType.Radial;
• Use the Field Wizard to add 3 Equal Area Y Fields from 0 to 10: sysField.ApplyFieldWizard(ZOSAPI.SystemData.FieldPattern.EqualAreaY,3,10,0,0,1,true,false);
The last three arguments (1, true, false) represent: Start At row 1, check the option Overwrite and uncheck Use Pickups, respectively.
• Use the Quadrature algorithm to define 6 wavelengths from 0.486 microns to 0.656 microns: TheSystemData.Wavelengths.GaussianQuadrature(0.486,0.656,ZOSAPI.SystemData.QuadratureSteps.S6);
• Use the Preset option to define Wavelengths: TheSystemData.Wavelengths.SelectWavelengthPreset(ZOSAPI.SystemData.WavelengthPreset.FdC_Visible);
• Read the number of fields: num_fields=TheSystem.SystemData.Fields.NumberOfFields;

## Analysis

### Definition

As defined in the Help File, the Analyses property gives us access to analysis features within OpticStudio.
TheAnalyses = ThePrimarySystem.Analyses;

### How to use it

Here are some useful commands to run analyses:

• Run a new analysis: TheSystem.Analyses.New_Analysis(ZOSAPI.Analysis.AnalysisIDM AnalysisType)
For example, to run a ray fan analysis:
TheRayFan = TheSystem.Analyses.New_Analysis(ZOSAPI.Analysis.AnalysisIDM.RayFan);
Some analyses can be open with their own function:
TheRayFan = TheSystem.Analyses.New_RayFan();
• Check if the analysis has implemented settings: TheRayFan.HasAnalysisSpecificSettings;
• Get settings: TheRayFan_Settings = TheRayFan.GetSettings();
• Modify the settings if the settings are implemented.
For example, to change the number of rays: TheRayFan_Settings.NumberOfRays = 100;
To change the wavelength: TheRayFan_Settings.Wavelength.SetWavelengthNumber(0);
• Modify the settings if they are not implemented using the ModifySettings property:
analysisSettings.SaveTo(cfgFile);
analysisSettings.ModifySettings(cfgFile, 'SHA_ROTX', '90');    analysisSettings.LoadFrom(cfgFile);    System.IO.File.Delete(cfgFile);        
• Apply setting:  TheRayFan.ApplyAndWaitForCompletion();
• Get results: TheRayFan_Results = TheRayFan.GetResults();
• Read results: this depends on the analysis that was executed. For more information, see the article "Generating a list of output data types for each analysis in the ZOS-API".
For example, the sample code 23 reads the Ray Fan analysis results using DataSeries.
for field = 1:max_num_field
     x = ray_results.DataSeries(field * 2 - 1).XData.Data.double;      y = ray_results.DataSeries(field * 2 - 1).YData.Data.double;
end;

## Editors

### Definition

Editors are a set of spreadsheets to enter lens data, objects data, operands data. The Editors include The Lens Data Editor (LDE), The Nonsequential Component Editor (NCE), The Merit Function Editor (MFE), The Multiconfiguration Editor (MCE), The Tolerance Data Editor (TDE).

TheLDE = TheSystem.LDE;

### How to use it

The functions are similar between the Editors. LDE will work on Surface, NCE will work on Objects, MFE, MCE and TDE will work on Operands and MCE will work on Configurations.

Here are some of the most common functions for TheLDE:

• Add a new surface: TheLDE.AddSurface();
• Insert a new surface at a specified surface number: TheLDE.InsertNewSurfaceAt(1);
• Remove one or certain number of surfaces from a specified surface number: TheLDE.RemoveSurfacesAt(1,3);
• Copy and paste the specified number of surfaces from one location to another : TheLDE.CopySurfaces(1,3,3);
The first argument is the first surface to copy, the second artgument is the number of surfaces to copy and the last argument is the surface number to paste at.
• Access a defined surface: TheLDE.GetSurfaceAt(1);
• Change a surface type: surf1_type=surf1.GetSurfaceTypeSettings(ZOSAPI.Editors.LDE.SurfaceType.EvenAspheric); surf1.ChangeType(surf1_type);
• Get or set values of the Radius, Thickness, SemiDiameter, ChipZone, Conic, TCE, Comment, Material, Coating: surf1.Comment=  'Add comment here';
solve_MarginalRayHeight= surf1.ThicknessCell.CreateSolveType(ZOSAPI.Editors.SolveType.MarginalRayHeight);   solve_MarginalRayHeight.PupilZone=0.5; surf1.ThicknessCell.SetSolveData(solve_MarginalRayHeight); surf1.RadiusCell.MakeSolveVariable();
• Change the value of a parameter: par2= surf1.GetSurfaceCell(ZOSAPI.Editors.LDE.SurfaceColumn.Par2); par2.DoubleValue= 0.0005;
• Change the aperture property of surface1 to a Circular Aperture :
aperdata=surf1.ApertureData; circular_aper=aperdata.CreateApertureTypeSettings(ZOSAPI.Editors.LDE.SurfaceApertureTypes.CircularAperture); circular_aper.MaximumRadius=0.5; aperdata.ChangeApertureTypeSettings(circular_aper);
• Access tools of the editor tool bar:  RunTool_ConvertLocalToGlobalCoordinates(int, int, int)

## IOpticalSystemTools ThePrimarySystem.Tools

### Definition

As defined in the Help File, each Optical System provides access to the System Tools. Only one tool can be run at a time on a given Optical System.

TheSystem.Tools

### How to use it

The syntax is similar between the Tools. To prepare a Tool for Running, you first open it, define the settings and then run it.

testFile = System.String.Concat(sampleDir, '\Sequential\Objectives\Cooke 40 degree field.zar'); testFolder = System.String.Concat(sampleDir, '\test\');
loadZAR=TheSystem.Tools.OpenRestoreZAR();
loadZAR.SetFileName(testFile); loadZAR.SetOutputFolder(testFolder); loadZAR.SetFilesAllOverwrite();
loadZAR.RunAndWaitForCompletion();
loadZAR.Close();

Here are some of the most common tools available in TheSystem.Tools.

• Create Archive:createZAR=TheSystem.Tools.OpenCreateZAR();
• Export the current lens data to a file as a CAD File: ToolExportCAD = TheSystem.Tools.OpenExportCAD();
• Convert file to non-sequential file: convertNSmode = TheSystem.Tools.OpenConvertToNSCGroup();
• Run Quick Focus: quickFocus = TheSystem.Tools.OpenQuickFocus();
• Remove all variables: TheSystem.Tools.RemoveAllVariables();
• Run a local optimization: LocalOpt = TheSystem.Tools.OpenLocalOptimization();
• Run a Batch ray trace: raytrace = TheSystem.Tools.OpenBatchRayTrace(); For more information see Batch Processing of Ray Trace Data using ZOS-API in MATLAB
• Open Tolerancing: tol = TheSystem.Tools.OpenTolerancing();
• Calculate a Merit Function: MFcalculator=TheSystem.Tools.OpenMeritFunctionCalculator();
• Calculate a Spot Radius: SpotCalculator= TheSystem.Tools.OpenRMSSpotRadiusCalculator();
• Insert lens from stock lens catalogs at surface 3: Lenscat=TheSystem.Tools.OpenLensCatalogs();

Here are some of the most common tools in non-sequential available in TheSystem.Tools.

Previous article: ZOS-API modes and sample files
Next article:
For Matlab users: Tips and tricks
For other users: How do I perform analysis of my system using the ZOS-API?

KA-01836

4 out of 5 found this helpful