Skip to main content

ZOS-API interface 2024 R1

PythonStandalone_22_seq_spot_diagram

Last update: 17.07.2025
1import clr, os, winreg
2from itertools import islice
3
4import matplotlib.pyplot as plt
5import numpy as np
6from System import Enum, Int32, Double
7
8class PythonStandaloneApplication(object):
9 class LicenseException(Exception):
10 pass
11 class ConnectionException(Exception):
12 pass
13 class InitializationException(Exception):
14 pass
15 class SystemNotPresentException(Exception):
16 pass
17
18 def __init__(self, path=None):
19 # determine location of ZOSAPI_NetHelper.dll & add as reference
20 aKey = winreg.OpenKey(winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER), r"Software\Zemax", 0, winreg.KEY_READ)
21 zemaxData = winreg.QueryValueEx(aKey, 'ZemaxRoot')
22 NetHelper = os.path.join(os.sep, zemaxData[0], r'ZOS-API\Libraries\ZOSAPI_NetHelper.dll')
23 winreg.CloseKey(aKey)
24 clr.AddReference(NetHelper)
25 import ZOSAPI_NetHelper
26
27 # Find the installed version of OpticStudio
28 if path is None:
29 isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize()
30 else:
31 # Note -- uncomment the following line to use a custom initialization path
32 isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize(path)
33
34 # determine the ZOS root directory
35 if isInitialized:
36 dir = ZOSAPI_NetHelper.ZOSAPI_Initializer.GetZemaxDirectory()
37 else:
38 raise PythonStandaloneApplication.InitializationException("Unable to locate Zemax OpticStudio. Try using a hard-coded path.")
39
40 # add ZOS-API referencecs
41 clr.AddReference(os.path.join(os.sep, dir, "ZOSAPI.dll"))
42 clr.AddReference(os.path.join(os.sep, dir, "ZOSAPI_Interfaces.dll"))
43 import ZOSAPI
44
45 # create a reference to the API namespace
46 self.ZOSAPI = ZOSAPI
47
48 # create a reference to the API namespace
49 self.ZOSAPI = ZOSAPI
50
51 # Create the initial connection class
52 self.TheConnection = ZOSAPI.ZOSAPI_Connection()
53
54 if self.TheConnection is None:
55 raise PythonStandaloneApplication.ConnectionException("Unable to initialize .NET connection to ZOSAPI")
56
57 self.TheApplication = self.TheConnection.CreateNewApplication()
58 if self.TheApplication is None:
59 raise PythonStandaloneApplication.InitializationException("Unable to acquire ZOSAPI application")
60
61 if self.TheApplication.IsValidLicenseForAPI == False:
62 raise PythonStandaloneApplication.LicenseException("License is not valid for ZOSAPI use")
63
64 self.TheSystem = self.TheApplication.PrimarySystem
65 if self.TheSystem is None:
66 raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")
67
68 def __del__(self):
69 if self.TheApplication is not None:
70 self.TheApplication.CloseApplication()
71 self.TheApplication = None
72
73 self.TheConnection = None
74
75 def OpenFile(self, filepath, saveIfNeeded):
76 if self.TheSystem is None:
77 raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")
78 self.TheSystem.LoadFile(filepath, saveIfNeeded)
79
80 def CloseFile(self, save):
81 if self.TheSystem is None:
82 raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")
83 self.TheSystem.Close(save)
84
85 def SamplesDir(self):
86 if self.TheApplication is None:
87 raise PythonStandaloneApplication.InitializationException("Unable to acquire ZOSAPI application")
88
89 return self.TheApplication.SamplesDir
90
91 def ExampleConstants(self):
92 if self.TheApplication.LicenseStatus == self.ZOSAPI.LicenseStatusType.PremiumEdition:
93 return "Premium"
94 elif self.TheApplication.LicenseStatus == self.ZOSAPI.LicenseStatusTypeProfessionalEdition:
95 return "Professional"
96 elif self.TheApplication.LicenseStatus == self.ZOSAPI.LicenseStatusTypeStandardEdition:
97 return "Standard"
98 else:
99 return "Invalid"
100
101 def reshape(self, data, x, y, transpose = False):
102 """Converts a System.Double[,] to a 2D list for plotting or post processing
103
104 Parameters
105 ----------
106 data : System.Double[,] data directly from ZOS-API
107 x : x width of new 2D list [use var.GetLength(0) for dimension]
108 y : y width of new 2D list [use var.GetLength(1) for dimension]
109 transpose : transposes data; needed for some multi-dimensional line series data
110
111 Returns
112 -------
113 res : 2D list; can be directly used with Matplotlib or converted to
114 a numpy array using numpy.asarray(res)
115 """
116 if type(data) is not list:
117 data = list(data)
118 var_lst = [y] * x;
119 it = iter(data)
120 res = [list(islice(it, i)) for i in var_lst]
121 if transpose:
122 return self.transpose(res);
123 return res
124
125 def transpose(self, data):
126 """Transposes a 2D list (Python3.x or greater).
127
128 Useful for converting mutli-dimensional line series (i.e. FFT PSF)
129
130 Parameters
131 ----------
132 data : Python native list (if using System.Data[,] object reshape first)
133
134 Returns
135 -------
136 res : transposed 2D list
137 """
138 if type(data) is not list:
139 data = list(data)
140 return list(map(list, zip(*data)))
141
142if __name__ == '__main__':
143 zos = PythonStandaloneApplication()
144
145 # load local variables
146 ZOSAPI = zos.ZOSAPI
147 TheApplication = zos.TheApplication
148 TheSystem = zos.TheSystem
149 if not os.path.exists(TheApplication.SamplesDir + "\\API\\Python"):
150 os.makedirs(TheApplication.SamplesDir + "\\API\\Python")
151
152 # Set up primary optical system
153 sampleDir = TheApplication.SamplesDir
154 file = "Double Gauss 28 degree field.zos"
155 testFile = sampleDir + "\\Sequential\\Objectives\\" + file
156 TheSystem.LoadFile(testFile, False)
157
158 #! [e22s01_py]
159 # Set up Batch Ray Trace
160 raytrace = TheSystem.Tools.OpenBatchRayTrace()
161 nsur = TheSystem.LDE.NumberOfSurfaces
162 max_rays = 30
163 normUnPolData = raytrace.CreateNormUnpol((max_rays + 1) * (max_rays + 1), ZOSAPI.Tools.RayTrace.RaysType.Real, nsur)
164 #! [e22s01_py]
165
166 #! [e22s02_py]
167 # Define batch ray trace constants
168 hx = 0.0
169 max_wave = TheSystem.SystemData.Wavelengths.NumberOfWavelengths
170 num_fields = TheSystem.SystemData.Fields.NumberOfFields
171 hy_ary = np.array([0, 0.707, 1])
172 #! [e22s02_py]
173
174 # Initialize x/y image plane arrays
175 x_ary = np.empty((num_fields, max_wave, ((max_rays + 1) * (max_rays + 1))))
176 y_ary = np.empty((num_fields, max_wave, ((max_rays + 1) * (max_rays + 1))))
177
178 #! [e22s03_py]
179 # Determine maximum field in Y only
180 max_field = 0.0
181 for i in range(1, num_fields + 1):
182 if (TheSystem.SystemData.Fields.GetField(i).Y > max_field):
183 max_field = TheSystem.SystemData.Fields.GetField(i).Y
184 #! [e22s03_py]
185
186 plt.rcParams["figure.figsize"] = (15, 4)
187 colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k')
188
189 if TheSystem.SystemData.Fields.GetFieldType() == ZOSAPI.SystemData.FieldType.Angle:
190 field_type = 'Angle'
191 elif TheSystem.SystemData.Fields.GetFieldType() == ZOSAPI.SystemData.FieldType.ObjectHeight:
192 field_type = 'Height'
193 elif TheSystem.SystemData.Fields.GetFieldType() == ZOSAPI.SystemData.FieldType.ParaxialImageHeight:
194 field_type = 'Height'
195 elif TheSystem.SystemData.Fields.GetFieldType() == ZOSAPI.SystemData.FieldType.RealImageHeight:
196 field_type = 'Height'
197
198 for field in range(1, len(hy_ary) + 1):
199 plt.subplot(1, 3, field, aspect='equal').set_title('Hy: %.2f (%s)' % (hy_ary[field - 1] * max_field, field_type))
200
201 for wave in range(1, max_wave + 1):
202
203 #! [e22s04_py]
204 # Adding Rays to Batch, varying normalised object height hy
205 normUnPolData.ClearData()
206 waveNumber = wave
207 #for i = 1:((max_rays + 1) * (max_rays + 1))
208 for i in range(1, (max_rays + 1) * (max_rays + 1) + 1):
209
210 px = np.random.random() * 2 - 1
211 py = np.random.random() * 2 - 1
212
213 while (px*px + py*py > 1):
214 py = np.random.random() * 2 - 1
215 normUnPolData.AddRay(waveNumber, hx, hy_ary[field - 1], px, py, Enum.Parse(ZOSAPI.Tools.RayTrace.OPDMode, "None"))
216 #! [e22s04_py]
217
218 raytrace.RunAndWaitForCompletion()
219
220 #! [e22s05_py]
221 # Read batch raytrace and display results
222 normUnPolData.StartReadingResults()
223
224 # Python NET requires all arguments to be passed in as reference, so need to have placeholders
225 sysInt = Int32(1)
226 sysDbl = Double(1.0)
227
228 output = normUnPolData.ReadNextResult(sysInt, sysInt, sysInt,
229 sysDbl, sysDbl, sysDbl, sysDbl, sysDbl, sysDbl, sysDbl, sysDbl, sysDbl, sysDbl, sysDbl);
230
231 while output[0]: # success
232 if ((output[2] == 0) and (output[3] == 0)): # ErrorCode & vignetteCode
233 x_ary[field - 1, wave - 1, output[1] - 1] = output[4] # X
234 y_ary[field - 1, wave - 1, output[1] - 1] = output[5] # Y
235 output = normUnPolData.ReadNextResult(sysInt, sysInt, sysInt,
236 sysDbl, sysDbl, sysDbl, sysDbl, sysDbl, sysDbl, sysDbl, sysDbl, sysDbl, sysDbl, sysDbl);
237 #! [e22s05_py]
238 temp = plt.plot(np.squeeze(x_ary[field - 1, wave - 1, :]), np.squeeze(y_ary[field - 1, wave - 1, :]), '.', ms = 1, color = colors[wave - 1])
239
240 plt.suptitle('Spot Diagram: %s' % (os.path.basename(testFile)))
241 plt.subplots_adjust(wspace=0.8)
242 plt.draw()
243
244 #! [e22s06_py]
245 # Spot Diagram Analysis Results
246 spot = TheSystem.Analyses.New_Analysis(ZOSAPI.Analysis.AnalysisIDM.StandardSpot)
247 spot_setting = spot.GetSettings()
248 spot_setting.Field.SetFieldNumber(0)
249 spot_setting.Wavelength.SetWavelengthNumber(0)
250 spot_setting.ReferTo = ZOSAPI.Analysis.Settings.RMS.ReferTo.Centroid
251 #! [e22s06_py]
252
253 #! [e22s07_py]
254 # extract RMS & Geo spot size for field points
255 spot.ApplyAndWaitForCompletion()
256 #spot_results = spot.GetResults()
257 spot_results = spot.GetResults()
258 print('RMS radius: %6.3f %6.3f %6.3f' % (spot_results.SpotData.GetRMSSpotSizeFor(1, 1), spot_results.SpotData.GetRMSSpotSizeFor(2, 1), spot_results.SpotData.GetRMSSpotSizeFor(3, 1)))
259 print('GEO radius: %6.3f %6.3f %6.3f' % (spot_results.SpotData.GetGeoSpotSizeFor(1, 1), spot_results.SpotData.GetGeoSpotSizeFor(2, 1), spot_results.SpotData.GetGeoSpotSizeFor(3, 1)))
260 #! [e22s07_py]
261
262 # This will clean up the connection to OpticStudio.
263 # Note that it closes down the server instance of OpticStudio, so you for maximum performance do not do
264 # this until you need to.
265 del zos
266 zos = None
267
268 # place plt.show() after clean up to release OpticStudio from memory
269 plt.show()
Definition: ZemaxService.cs:198

Connect with Ansys