Skip to main content

ZOS-API interface 2025 R2

PythonStandalone_05_Read_ZRD_File

Last update: 16.07.2025
1import clr, os, winreg
2from itertools import islice
3
4class PythonStandaloneApplication(object):
5 class LicenseException(Exception):
6 pass
7 class ConnectionException(Exception):
8 pass
9 class InitializationException(Exception):
10 pass
11 class SystemNotPresentException(Exception):
12 pass
13
14 def __init__(self, path=None):
15 # determine location of ZOSAPI_NetHelper.dll & add as reference
16 aKey = winreg.OpenKey(winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER), r"Software\Zemax", 0, winreg.KEY_READ)
17 zemaxData = winreg.QueryValueEx(aKey, 'ZemaxRoot')
18 NetHelper = os.path.join(os.sep, zemaxData[0], r'ZOS-API\Libraries\ZOSAPI_NetHelper.dll')
19 winreg.CloseKey(aKey)
20 clr.AddReference(NetHelper)
21 import ZOSAPI_NetHelper
22
23 # Find the installed version of OpticStudio
24 if path is None:
25 isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize()
26 else:
27 # Note -- uncomment the following line to use a custom initialization path
28 isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize(path)
29
30 # determine the ZOS root directory
31 if isInitialized:
32 dir = ZOSAPI_NetHelper.ZOSAPI_Initializer.GetZemaxDirectory()
33 else:
34 raise PythonStandaloneApplication.InitializationException("Unable to locate Zemax OpticStudio. Try using a hard-coded path.")
35
36 # add ZOS-API referencecs
37 clr.AddReference(os.path.join(os.sep, dir, "ZOSAPI.dll"))
38 clr.AddReference(os.path.join(os.sep, dir, "ZOSAPI_Interfaces.dll"))
39 import ZOSAPI
40
41 # create a reference to the API namespace
42 self.ZOSAPI = ZOSAPI
43
44 # create a reference to the API namespace
45 self.ZOSAPI = ZOSAPI
46
47 # Create the initial connection class
48 self.TheConnection = ZOSAPI.ZOSAPI_Connection()
49
50 if self.TheConnection is None:
51 raise PythonStandaloneApplication.ConnectionException("Unable to initialize .NET connection to ZOSAPI")
52
53 self.TheApplication = self.TheConnection.CreateNewApplication()
54 if self.TheApplication is None:
55 raise PythonStandaloneApplication.InitializationException("Unable to acquire ZOSAPI application")
56
57 if self.TheApplication.IsValidLicenseForAPI == False:
58 raise PythonStandaloneApplication.LicenseException("License is not valid for ZOSAPI use")
59
60 self.TheSystem = self.TheApplication.PrimarySystem
61 if self.TheSystem is None:
62 raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")
63
64 def __del__(self):
65 if self.TheApplication is not None:
66 self.TheApplication.CloseApplication()
67 self.TheApplication = None
68
69 self.TheConnection = None
70
71 def OpenFile(self, filepath, saveIfNeeded):
72 if self.TheSystem is None:
73 raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")
74 self.TheSystem.LoadFile(filepath, saveIfNeeded)
75
76 def CloseFile(self, save):
77 if self.TheSystem is None:
78 raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")
79 self.TheSystem.Close(save)
80
81 def SamplesDir(self):
82 if self.TheApplication is None:
83 raise PythonStandaloneApplication.InitializationException("Unable to acquire ZOSAPI application")
84
85 return self.TheApplication.SamplesDir
86
87 def ExampleConstants(self):
88 if self.TheApplication.LicenseStatus == self.ZOSAPI.LicenseStatusType.PremiumEdition:
89 return "Premium"
90 elif self.TheApplication.LicenseStatus == self.ZOSAPI.LicenseStatusTypeProfessionalEdition:
91 return "Professional"
92 elif self.TheApplication.LicenseStatus == self.ZOSAPI.LicenseStatusTypeStandardEdition:
93 return "Standard"
94 else:
95 return "Invalid"
96
97 def reshape(self, data, x, y, transpose = False):
98 """Converts a System.Double[,] to a 2D list for plotting or post processing
99
100 Parameters
101 ----------
102 data : System.Double[,] data directly from ZOS-API
103 x : x width of new 2D list [use var.GetLength(0) for dimension]
104 y : y width of new 2D list [use var.GetLength(1) for dimension]
105 transpose : transposes data; needed for some multi-dimensional line series data
106
107 Returns
108 -------
109 res : 2D list; can be directly used with Matplotlib or converted to
110 a numpy array using numpy.asarray(res)
111 """
112 if type(data) is not list:
113 data = list(data)
114 var_lst = [y] * x;
115 it = iter(data)
116 res = [list(islice(it, i)) for i in var_lst]
117 if transpose:
118 return self.transpose(res);
119 return res
120
121 def transpose(self, data):
122 """Transposes a 2D list (Python3.x or greater).
123
124 Useful for converting mutli-dimensional line series (i.e. FFT PSF)
125
126 Parameters
127 ----------
128 data : Python native list (if using System.Data[,] object reshape first)
129
130 Returns
131 -------
132 res : transposed 2D list
133 """
134 if type(data) is not list:
135 data = list(data)
136 return list(map(list, zip(*data)))
137
138if __name__ == '__main__':
139 zos = PythonStandaloneApplication()
140
141 # load local variables
142 ZOSAPI = zos.ZOSAPI
143 TheApplication = zos.TheApplication
144 TheSystem = zos.TheSystem
145 Logic = ['False', 'True']
146
147 # Open file and set Analysis Ryas to only 10
148 testFile = TheApplication.SamplesDir + r'\Non-sequential\Miscellaneous\Digital_projector_flys_eye_homogenizer.zos'
149 TheSystem.LoadFile(testFile, False)
150 print(TheSystem.SystemFile)
151 TheSystem.NCE.GetObjectAt(1).GetObjectCell(ZOSAPI.Editors.NCE.ObjectColumn.Par2).IntegerValue = 1
152
153 #! [e27s01_py]
154 # Trace and save a ZRD file for test later
155 NSCRayTrace = TheSystem.Tools.OpenNSCRayTrace()
156 NSCRayTrace.SplitNSCRays = True
157 NSCRayTrace.ScatterNSCRays = False
158 NSCRayTrace.UsePolarization = True
159 NSCRayTrace.IgnoreErrors = True
160 NSCRayTrace.SaveRays = True
161 NSCRayTrace.SaveRaysFile = 'Digital_projector_flys_eye_homogenizer.ZRD'
162 NSCRayTrace.ClearDetectors(0)
163 NSCRayTrace.RunAndWaitForCompletion()
164 NSCRayTrace.Close()
165 #! [e27s01_py]
166
167 #! [e27s02_py]
168 ZRDReader = TheSystem.Tools.OpenRayDatabaseReader()
169 ZRDReader.ZRDFile = TheApplication.SamplesDir + r'\Non-sequential\Miscellaneous\Digital_projector_flys_eye_homogenizer.ZRD'
170 print(TheApplication.SamplesDir + r'\Non-sequential\Miscellaneous\Digital_projector_flys_eye_homogenizer.ZRD')
171
172
173 ZRDReader.RunAndWaitForCompletion()
174 if ZRDReader.Succeeded == 0:
175 print('Raytracing failed!\n')
176 print(ZRDReader.ErrorMessage)
177 else:
178 print('Raytracing completed!\n')
179 #! [e27s02_py]
180
181 #! [e27s03_py]
182 ZRDResult = ZRDReader.GetResults()
183 # ReadNExtResult() returns data ray by ray
184 success_NextResult, rayNumber, waveIndex, wlUM, numSegments = ZRDResult.ReadNextResult(0, 0, 0, 0)
185 while success_NextResult == True:
186 print('\n\n\nsuccess_NextResult: %s, rayNumber: %d, waveIndex: %d, wlUM: %f, numSegments: %d\n\n' %
187 (Logic[success_NextResult], rayNumber, waveIndex, wlUM, numSegments))
188 segdata = ZRDResult.ReadNextSegmentFull(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
189 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
190 21, 22, 23, 24, 25, 26, 27, 28, 29)
191 while segdata[0] == True:
192 print('''success_NextSegmentFull: %s, segmentLevel: %d, segmentParent: %d,
193hitObj: %d, hitFace: %d, insideOf: %d, status: %s,
194x: %f, y: %f, z: %f,l: %f, m: %f, n: %f,
195exr: %f, exi: %f, eyr: %f, eyi: %f, ezr: %f, ezi: %f,
196intensity: %f, pathLength: %f, xybin: %d, lmbin: %d,
197xNorm: %f, yNorm: %f, zNorm: %f,
198index: %f, startingPhase: %f, phaseOf: %f, phaseAt: %f\n''' %
199 (Logic[segdata[0]], segdata[1], segdata[2], segdata[3], segdata[4], segdata[5], segdata[6],
200 segdata[7], segdata[8], segdata[9], segdata[10], segdata[11], segdata[12], segdata[13],
201 segdata[14], segdata[15], segdata[16], segdata[17], segdata[18], segdata[19], segdata[20],
202 segdata[21], segdata[22], segdata[23], segdata[24], segdata[25], segdata[26], segdata[27],
203 segdata[28], segdata[29]))
204 segdata = ZRDResult.ReadNextSegmentFull(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
205 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
206 21, 22, 23, 24, 25, 26, 27, 28, 29)
207 success_NextResult, rayNumber, waveIndex, wlUM, numSegments = ZRDResult.ReadNextResult(0, 0, 0, 0)
208
209 ZRDReader.Close()
210 #! [e27s03_py]
211
212
213 # This will clean up the connection to OpticStudio.
214 # Note that it closes down the server instance of OpticStudio, so you for maximum performance do not do
215 # this until you need to.
216 del zos
217 zos = None
Definition: ZemaxService.cs:198

Connect with Ansys