Share your solutions or ask questions about the ZOS-API, ZPL, or DLLs. Code shared in these spaces is not reviewed by Zemax except for the Code Exchange.
Run a Macro from ZOSAPI
Hi! Is there a way to run a macro from ZOS-API? I have a macro that does some calculation on the currently opened Zemax model and outputs some data. In a Python script I want to make some modifications to the Zemax model using the ZOS-API and then run my macro. Is that possible? Best, Erik
Run python code from macro and get output variables to OS macro
Hi, I would like to run a python script from a macro (could be a python executable), then get some of the outputed values in the macro. Then I would like to write this values in a merit function from the macro. Is there a simple way to do it or some starting code? Thanks, Jose
Calculate the "field Type" "Angle" from the "field Type" "Real Image Height" with a ZPL
Is it possible to calculate the 'field Type' 'Angle' (Code 0) from the 'field Type' 'Real Image Height' (Code 3) with a ZPL script? It is basically what the Zemax 'Field data editor' offers with the 'Convert to' option. However, I do not need to *convert* the field type, but just have to determine the value. With 'Single Ray Trace' as well as with the operand 'RAID', I only get one angle. But I need the two angles as defined for the 'field Type' 'Angle' Thank you and best regards, Christof.
SkewRaysGaussian: need DLL supporting general astigmatism
I was pleased to see the new NSC Source DLL 'SkewRaysCircular.dll' added in the May 19 release (OpticStudio 20.2). We have immediate use for it in modeling our systems. It was inspired by the similar (sequential) User Defined Surface DLLs discussed in Paul Colbourne's webinar and KnowledgeBase Article KA-01772, which allows optimization of generally astigmatic Gaussian beams in Sequential mode. But I was disappointed to see that the new Non-Sequential Source DLL only models CIRCULAR Gaussian beams with no astigmatism, unlike the Sequential capabilities that were supplied by Dr. Colbourne, which accommodate general astigmatism! I suggest updating and replacing SkewRaysCircular.dll with a new, more general, Source DLL, renamed appropriately, e.g., SkewRaysGaussianXY.dll , that DOES support general astigmatism. This would seem simple enough to implement starting from the existing SkewRaysCircular.dll: add new pairs of parameters for WaistX, WaistY, (and/or SIzeX, Siz
Physical Optics Propagation (POP) - API settings
Hi, In the ZOSAPI, the settings for the Physical Optics Propagation analysis feature are now fully implemented: So as an example, we may set the settings in the 'General' and 'Beam Definition' tabs using the ZOSAPI in MATLAB: TheSystem = TheApplication.PrimarySystem; TheAnalyses = TheSystem.Analyses; newPOP = TheAnalyses.New_Analysis(ZOSAPI.Analysis.AnalysisIDM.PhysicalOpticsPropagation); newPOP.HasAnalysisSpecificSettings; newPOP_Settings = newPOP.Settings(); newPOP_Settings.Wavelength.SetWavelengthNumber(1); newPOP_Settings.Field.SetFieldNumber(1); newPOP_Settings.StartSurface.SetSurfaceNumber(1); newPOP_Settings.EndSurface.SetSurfaceNumber(4); newPOP_Settings.SurfaceToBeam = 0.0; newPOP_Settings.UsePolarization = true; newPOP_Settings.SeparateXY = false; newPOP_Settings.UseDiskStorage = false; newPOP_Settings.BeamType = ZOSAPI.Analysis.PhysicalOptics.POPBeamTypes.GaussianWaist; newPOP_Settings.XSampling = ZOSAPI.Analysis.SampleSizes.S_128x128; newPOP
How to save detector image as 24 bit, uint8, rbg format when running ZEMAX via MATLAB
Hi, I am running some simulations in ZEMAX via MATLAB for image analysis after changing some parameters. I am running in non-sequential mode and detector type rectangle below. My issue is getting the wrong image format via MATLAB. The detector image I save manually in detector viewer in ZEMAX has format is a 800x800x8 uint8 with 24 bit image. This is what I want to use for further analysis in MATLAB, but its cumbersum to manually save each image for each simulation when you do many. I just want to run this in the background and save time. Thus, I want to save the detector image (suppress frame) after each ray trace after changing some parameters with a for loop. I found a way to run the simulation in MATLAB, but extracting the same image has been difficult. I extract the detector image from ZEMAX via the code; % Get detector data data = NET.createArray('System.Double', TheNCE.GetDetectorSize(30)); &nb
DLL (Source): Non-sequential Astigmatic Gaussian
This Source DLL models an Astigmatic Gaussian Source. It is based on rays but the statistical distribution of rays gives a picture of a diffracting Gaussian beam. It is valid for small angles (paraxial approximation) and when propagating in free space. So clipping at apertures and aberrations will give incorrect results.w0x, w0y are the real beam waist radii (defined at the 1/e2 intensity point) in the XZ and YZ planes. They includes M^2. z0x, z0y are the positions of the beam waist in the XZ and YZ planes. z0<0: in propagation direction if the waist is located before source. M^2x, M^2y are the quality factors in the XZ and YZ planes.For more information, see "Representation of a Gaussian beam by rays" by P. P. Crooker, W. B. Colson, and J. Blau - Physics Department, Naval Postgraduate School, Monterey, California 93943Authors:Steffen Erhard and @Dirk Broemme Click here to download Date Version OpticStudio Version Comment 2020/05/06 1.0 21.1.2 Creation 2023/0
ZOSAPI_NetHelper cannot be added
Hi. I am using the ZOS-API for Python and try to switch to the new recommended method of using PythonNET instead of the COM interface. To do so, I created a new Python template using 'Programming>Python>Interactive Extension' (same problem occurs with 'Standalone Application'). Running this template fails when trying to add the NetHelper DLL: import clr, os, winreg from itertools import islice # determine the Zemax working directory aKey = winreg.OpenKey(winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER), r'Software\Zemax', 0, winreg.KEY_READ) zemaxData = winreg.QueryValueEx(aKey, 'ZemaxRoot') NetHelper = os.path.join(os.sep, zemaxData, r'ZOS-API\Libraries\ZOSAPI_NetHelper.dll') winreg.CloseKey(aKey) # add the NetHelper DLL for locating the OpticStudio install folder clr.AddReference(NetHelper) import ZOSAPI_NetHelper --------------------------------------------------------------------------- FileNotFoundException Traceback (most recent call
ZPL Operand: Extract FWHM from non-sequential detector
Description: This macro will calculate the approximate FWHM of a near-Normal distribution of data. This macro assumes symmetry about the maximum value and assumes a minimal amount of noise between 0 and the maximum. The macro will update the Detector Viewer settings to a cross-section view. Then, the data will be extracted and evaluated. When using the ZPL10 version of the macro, the approximate FWHM will be reported when Data = 0 for the X-direction, and Data = 1 for the Y-Direction. Use the Hx entry to specify the detector of interest. Language:ZPLUpdates:10/22/2021 - Stability and calculation updates. The calculation is now more robust. The code for finding the CFG file has been updated. See the ReadMe for more information. Download: Click here to download Date Version OpticStudio Version Comment 2019/10/15 1.0 19.4SP2 Creation 2020/10/14 2.0 20.3 Updated macro with the following - CFG file is programmatically calculated - FWHM index location calcul
Please throw errors instead of failing silently
It is a good practice to fail extremely loudly - if there is some issue, don't leave it up to the caller to detect the problem. Halt execution, and please throw an error. We've been using CAD files, and the server we have been using the ZOS API didn't have Solidworks installed. Because of that, the ZOS API just silently ignores those CAD files - no logging, nothing. As a result, we have months of simulations that have produced bad results. The answer I've gotten before is 'We rely on the user to handle errors'. This is terrible UX. How am I supposed to find problems? I make an exhaustive checklist that is 300 items long that validates each ZAR file the API ingests? How do I make that checklist in the first place? I don't see how I could have noticed this CAD issue. At the very least, please print out potential issues to the console. The best option for UX would be to throw errors.
Saving detector series data / img with ZPL
Hi all,I want to save data and images of detectors automatically with ZPL. So I made the ZPL code as below. For n = 2, 6, 1 ####### get Detector viewer in img. winnum = n+1 OpenAnalysisWindow "Dvr", cfgpath$ ExportJPG winnum, imgfile$ ####### get Detector viewer in dat. #ModifySettings cfgtxt$, DVW_SHOW, 1 # extraction middle row data from 2d data GetTextFile datfile$, "Dvr", cfgtxt$ , 1 ConvertFileFormat datfile$, 1 #Unicode to ANSINext Once I open all detector viewer windows, I tried to save images and data in detector number order. However, I couldn’t save each detector data/image because it cannot recognize the number of detector in this code. What should I do? Or, are there better method to do it? Please help me. Thanks in advance.
Possible to set Settings for "PhysicalOpticsPropagation" window via Matlab API?
Hello, I was wondering, if it is possible to define the Settings for a 'PhysicalOpticsPropagation' Window created in Matlab as follows: window = TheSystem.Analyses.New_Analysis(ZOSAPI.Analysis.AnalysisIDM.PhysicalOpticsPropagation) I am missing an option for "General", "Beam Definition", "Display", and so on.
How can I pull Peak Irradiance or Total Hits from the Detector Viewer analysis in the API?
Within the API, we are able to quickly pull Peak Irradiance, Total Power, and Total Hits by using the property GetDetectorData as described in the forum post 'Methods for extracting detector data through the API.' However, this property will not take into account an applied ZRD file. We can apply a ZRD file to a Detector Viewer window, so is there a way to extract the same information from there?
Extration of PSF and MTF data via Python
Hello Everyone, I have the model for an automotive camera lens. I also have the samples of the lenses to perform measurements.Here is what I would like to do with the model (I am an absolute novice in programming):I would like to specify points in the objects space (varying the object distance and the object height position) and would I would like to extract the Huygen’s MTF and PSF for all these points. I would also like to know the position of the image (of the point) on the imager.So far, I have understood that I can vary the object height points in Python, I am however, not sure how I can vary the object distance!I tried to use the example code for “Retrieve Data from FFT MTF” and made some modifications to extract the MTF information for my lens file. It seems to work for the FOV points (by object height) already specified in the lens model and a constant object distance but I would like to do the same for a list of points in the object space and would be nice if it can be automat
Explode CAD assembly and load Data in ZOS API
Hello, i am currently working on a Python program to automate as many process steps as possible in scattered light analysis. I don't have so much experience in Zemax API programming yet and have tried to get familiar with it using the example programs, the knowladgebase and ZOS help. My CAD file is a SolidWorks assembly, which I also inserted without any problems, but I would like to use the Explode command to split it into the individual parts for a better path analysis. Here my question is how to unzip my file correctly and if there is a more detailed article than the videos about the ZOS API Help, because this is not enough for me to understand the command structure. A second point is, I would like to have my data from PathAnalysis available as data in Python for evaluation, here I also did not manage to understand the program structure. So far I have only been able to make it useful by saving it as text first and reading it in afterwards. With kind regards Christian
DLL (User-Defined Surface): Sequential Hexagonal and Staggered Lens Array
These two User-defined surfaces DLL creates an array of hexagonal arranged lenses and an array of staggered lenses. The code is based on us_array.c.us_array_hex.dll has 4 parameters: the number of lenses in X and Y direction and the width and height of each lens.us_array_staggered.dll has 3 parameters: the number of lenses in X and Y direction and the width of the lens.Language: Cpp Click here to download Date Version OpticStudio Version Comment 2018/01/06 1.0 - Creation
Path Analysis Loss of Power and Atmospheric (Air) Losses
Hi,I’m using the Path Analysis feature (run from Matlab) to analyze how the light is going through a system. Path Analysis is a great feature!What I’m noticing is that if I add up the number of rays in the path analysis rows, they equal to the number of rays in the ray trace / and in the layout. However, if I add up the powers in the rows, there is a total loss of about 1.8%. I currently do not have any coatings set on the various components (struggling to get that to work for some unknown reason or the other). Just mirror/reflector and absorbers.Is there an atmospheric loss built into Zemax due to the air the light passes through? I tried setting the air pressure to zero in the System Explorer/Environment to try and simulate a vacuum, and it didn’t change anything. And, if there are air losses, I’d like to control them or set them to zero and calculate the losses numerically. Thanks!
Python Reading Writing Binary Files (ZRD, ZBF, DAT, SDF)
The download contains 3 Python scripts:a script to read / parse a ZRD (Zemax Ray Database) file a script to read / parse a Binary ZBF (Zemax Beam File) file a script to read / parse a Binary DAT / SDF Source File Click here to download Date Version OpticStudio Version Comment 2022/01/01 1.0 - Creation
RemotingException when running the BatchRayTrace with Python in Interactive Extension
Dear Zemax Community, When I try to use the BatchRayTrace tool from Python in an Interactive Extension, I get a RemotingException, which seem to be related to the use of the AddRay method in the IRayTraceNormUnpolData interface. To reproduce the issue, try making Example 23 into an Interactive Extension (instead of a Standalone Application). Alternatively, this is my code snippet for an Interactive Extension: from System import Enum, Int32, Double # Open the BatchRayTrace tool MyBatchRT = TheSystem.Tools.OpenBatchRayTrace() # Add an unpolarized-raytrace ToImageSurface = 3 MaxRays = 1 MyUnpolRT = MyBatchRT.CreateNormUnpol(MaxRays, ZOSAPI.Tools.RayTrace.RaysType.Real, ToImageSurface) WaveNumber = Int32(0) Hx = Double(0) Hy = Double(0) Px = Double(0) Py = Double(0) MyUnpolRT.AddRay(WaveNumber, Hx, Hy, Px, Py, Enum.Parse(ZOSAPI.Tools.RayTrace.OPDMode, 'None')) # Run the raytrace MyBatchRT.RunAndWaitForCompletion() # Close the BatchRayTrace tool MyBatchRT.Clos
Hi, i am new to Zemax and i tried to connect my lense system with Matlab through the ZOS-API interactive extension. As i run the template script the 'TheApplication' Object with all its properties should appear, but thats not the case. It is just showing in which folder it is found and nothing else. Furthermore i do not know how to load the lense system into this matlab file. Is there anything i missed out? If somebody could help a beginner that would be really nice. Best wishes, Julia.
How to check relative illumination at 'object' surface (verify the relative illumination theory)
Sometimes, we may design the system starting from the 'image' back to the 'object'. For example, this is often the case for those systems that are designed to be viewed by eye, like AR/VR, HUD. In this case, normally, if we want to check the relative illumination, we need to reverse the system to check because the tool 'Relative Illumination' only calculates that on last surface in the system.Here we will provide another way to calculate it using a macro so that you don't need to reverse the system.Note here we at the same time is also demoing how you can verify the calculation theory of the RI. RI is actually much easier to calculate if the system is reversely designed! First, by reading the following forum post, we know that relative illumination at each field is exactly linearly dependent to the area of the beam in cosine space in image space.So, here is the plan. We want to write a macro to calculate the beam area in cosine space for each field, normalize it, and then get the the R
Already have an account? Login
Enter your username or e-mail address. We'll send you an e-mail with instructions to reset your password.