PythonStandalone_04_pull_data_from_FFTMTF
Last update: 17.07.2025 1import clr, os, winreg
2from itertools import islice
3
4import matplotlib.pyplot as plt
5import numpy as np
6
7class PythonStandaloneApplication(object):
8 class LicenseException(Exception):
9 pass
10 class ConnectionException(Exception):
11 pass
12 class InitializationException(Exception):
13 pass
14 class SystemNotPresentException(Exception):
15 pass
16
17 def __init__(self, path=None):
18 # determine location of ZOSAPI_NetHelper.dll & add as reference
19 aKey = winreg.OpenKey(winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER), r"Software\Zemax", 0, winreg.KEY_READ)
20 zemaxData = winreg.QueryValueEx(aKey, 'ZemaxRoot')
21 NetHelper = os.path.join(os.sep, zemaxData[0], r'ZOS-API\Libraries\ZOSAPI_NetHelper.dll')
22 winreg.CloseKey(aKey)
23 clr.AddReference(NetHelper)
24 import ZOSAPI_NetHelper
25
26 # Find the installed version of OpticStudio
27 if path is None:
28 isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize()
29 else:
30 # Note -- uncomment the following line to use a custom initialization path
31 isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize(path)
32
33 # determine the ZOS root directory
34 if isInitialized:
35 dir = ZOSAPI_NetHelper.ZOSAPI_Initializer.GetZemaxDirectory()
36 else:
37 raise PythonStandaloneApplication.InitializationException("Unable to locate Zemax OpticStudio. Try using a hard-coded path.")
38
39 # add ZOS-API referencecs
40 clr.AddReference(os.path.join(os.sep, dir, "ZOSAPI.dll"))
41 clr.AddReference(os.path.join(os.sep, dir, "ZOSAPI_Interfaces.dll"))
42 import ZOSAPI
43
44 # create a reference to the API namespace
45 self.ZOSAPI = ZOSAPI
46
47 # create a reference to the API namespace
48 self.ZOSAPI = ZOSAPI
49
50 # Create the initial connection class
51 self.TheConnection = ZOSAPI.ZOSAPI_Connection()
52
53 if self.TheConnection is None:
54 raise PythonStandaloneApplication.ConnectionException("Unable to initialize .NET connection to ZOSAPI")
55
56 self.TheApplication = self.TheConnection.CreateNewApplication()
57 if self.TheApplication is None:
58 raise PythonStandaloneApplication.InitializationException("Unable to acquire ZOSAPI application")
59
60 if self.TheApplication.IsValidLicenseForAPI == False:
61 raise PythonStandaloneApplication.LicenseException("License is not valid for ZOSAPI use")
62
63 self.TheSystem = self.TheApplication.PrimarySystem
64 if self.TheSystem is None:
65 raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")
66
67 def __del__(self):
68 if self.TheApplication is not None:
69 self.TheApplication.CloseApplication()
70 self.TheApplication = None
71
72 self.TheConnection = None
73
74 def OpenFile(self, filepath, saveIfNeeded):
75 if self.TheSystem is None:
76 raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")
77 self.TheSystem.LoadFile(filepath, saveIfNeeded)
78
79 def CloseFile(self, save):
80 if self.TheSystem is None:
81 raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")
82 self.TheSystem.Close(save)
83
84 def SamplesDir(self):
85 if self.TheApplication is None:
86 raise PythonStandaloneApplication.InitializationException("Unable to acquire ZOSAPI application")
87
88 return self.TheApplication.SamplesDir
89
90 def ExampleConstants(self):
91 if self.TheApplication.LicenseStatus == self.ZOSAPI.LicenseStatusType.PremiumEdition:
92 return "Premium"
93 elif self.TheApplication.LicenseStatus == self.ZOSAPI.LicenseStatusTypeProfessionalEdition:
94 return "Professional"
95 elif self.TheApplication.LicenseStatus == self.ZOSAPI.LicenseStatusTypeStandardEdition:
96 return "Standard"
97 else:
98 return "Invalid"
99
100 def reshape(self, data, x, y, transpose = False):
101 from itertools import islice
102 if type(data) is not list:
103 data = list(data)
104 var_lst = [y] * x;
105 it = iter(data)
106 res = [list(islice(it, i)) for i in var_lst]
107 if transpose:
108 return self.transpose(data);
109 return res
110
111 def transpose(self, data):
112 if type(data) is not list:
113 data = list(data)
114 return list(map(list, zip(*data)))
115
116 def reshape(self, data, x, y, transpose = False):
117 """Converts a System.Double[,] to a 2D list for plotting or post processing
118
119 Parameters
120 ----------
121 data : System.Double[,] data directly from ZOS-API
122 x : x width of new 2D list [use var.GetLength(0) for dimension]
123 y : y width of new 2D list [use var.GetLength(1) for dimension]
124 transpose : transposes data; needed for some multi-dimensional line series data
125
126 Returns
127 -------
128 res : 2D list; can be directly used with Matplotlib or converted to
129 a numpy array using numpy.asarray(res)
130 """
131 if type(data) is not list:
132 data = list(data)
133 var_lst = [y] * x;
134 it = iter(data)
135 res = [list(islice(it, i)) for i in var_lst]
136 if transpose:
137 return self.transpose(res);
138 return res
139
140 def transpose(self, data):
141 """Transposes a 2D list (Python3.x or greater).
142
143 Useful for converting mutli-dimensional line series (i.e. FFT PSF)
144
145 Parameters
146 ----------
147 data : Python native list (if using System.Data[,] object reshape first)
148
149 Returns
150 -------
151 res : transposed 2D list
152 """
153 if type(data) is not list:
154 data = list(data)
155 return list(map(list, zip(*data)))
156
157if __name__ == '__main__':
158 zos = PythonStandaloneApplication()
159
160 # use http://matplotlib.org/ to plot line graph
161 # need to install this package before running this code
162
163 # load local variables
164 ZOSAPI = zos.ZOSAPI
165 TheApplication = zos.TheApplication
166 TheSystem = zos.TheSystem
167 sampleDir = TheApplication.SamplesDir
168
169 #! [e04s01_py]
170 # Open file
171 testFile = sampleDir + '\\Sequential\\Objectives\\Cooke 40 degree field.zos'
172 TheSystem.LoadFile(testFile, False)
173 #! [e04s01_py]
174
175 #! [e04s02_py]
176 # Create analysis
177 TheAnalyses = TheSystem.Analyses
178 newWin = TheAnalyses.New_FftMtf()
179 #! [e04s02_py]
180
181 #! [e04s03_py]
182 # Settings
183 newWin_Settings = newWin.GetSettings()
184 newWin_Settings.MaximumFrequency = 50
185 newWin_Settings.SampleSize = ZOSAPI.Analysis.SampleSizes.S_256x256
186 #! [e04s03_py]
187
188 #! [e04s04_py]
189 # Run Analysis
190 newWin.ApplyAndWaitForCompletion()
191 # Get Analysis Results
192 newWin_Results = newWin.GetResults()
193 #! [e04s04_py]
194
195
196 #! [e04s05_py]
197 # Read and plot data series
198 # NOTE: numpy functions are used to unpack and plot the 2D tuple for Sagittal & Tangential MTF
199 # You will need to import the numpy module to get this part of the code to work
200 colors = ('b','g','r','c', 'm', 'y', 'k')
201 for seriesNum in range(0,newWin_Results.NumberOfDataSeries, 1):
202 data = newWin_Results.GetDataSeries(seriesNum)
203
204 # get raw .NET data into numpy array
205 xRaw = data.XData.Data
206 yRaw = data.YData.Data
207
208 x = list(xRaw)
209 y = zos.reshape(yRaw, yRaw.GetLength(0), yRaw.GetLength(1), True)
210
211 plt.plot(x,y[0],color=colors[seriesNum])
212 plt.plot(x,y[1],linestyle='--',color=colors[seriesNum])
213 #! [e04s05_py]
214
215 # If you want to use numpy, you can replace the last 4 commands in the for loop with:
216 # x = np.array(tuple(xRaw))
217 # y = np.array(np.asarray(tuple(yRaw)).reshape(data.YData.Data.GetLength(0), data.YData.Data.GetLength(1)))
218 #
219 # plt.plot(x[:],y[:,0],color=colors[seriesNum])
220 # plt.plot(x[:],y[:,1],linestyle='--',color=colors[seriesNum])
221
222
223 # format the plot
224 plt.title('FFT MTF: ' + os.path.basename(testFile))
225 plt.xlabel('Spatial Frequency in cycles per mm')
226 plt.ylabel('Modulus of the OTF')
227 plt.legend([r'$0^\circ$ tangential',r'$0^\circ$ sagittal',r'$14^\circ$ tangential',r'$14^\circ$ sagittal',r'$20^\circ$ tangential',r'$20^\circ$ sagittal'])
228 plt.grid(True)
229
230 # This will clean up the connection to OpticStudio.
231 # Note that it closes down the server instance of OpticStudio, so you for maximum performance do not do
232 # this until you need to.
233 del zos
234 zos = None
235
236 # place plt.show() after clean up to release OpticStudio from memory
237 plt.show()
Definition: ZemaxService.cs:198