Skip to main content

ZOS-API interface 2024 R1

PythonStandalone_03_open_file_and_optimise

Last update: 17.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 sampleDir = TheApplication.SamplesDir
146
147 # creates a new API directory
148 if not os.path.exists(TheApplication.SamplesDir + "\\API\\Python"):
149 os.makedirs(TheApplication.SamplesDir + "\\API\\Python")
150
151 #! [e03s01_py]
152 # Open file
153 testFile = sampleDir + '\\API\\Python\\e01_new_file_and_quickfocus.zos'
154 if not os.path.exists(testFile):
155 # closes connection to ZOS; normally done at end of script
156 del zos
157 zos = None
158 sys.exit('You need to run Example 01 before running this example')
159 TheSystem.LoadFile(testFile, False)
160 testFile2 = sampleDir + '\\API\\Python\\e03_open_file_and_optimise.zos'
161 TheSystem.SaveAs(testFile2)
162 #! [e03s01_py]
163
164 #! [e03s02_py]
165 # Get Surfaces
166 TheLDE = TheSystem.LDE
167 Surface_1 = TheLDE.GetSurfaceAt(1)
168 Surface_2 = TheLDE.GetSurfaceAt(2)
169 Surface_3 = TheLDE.GetSurfaceAt(3)
170 #! [e03s02_py]
171
172 #! [e03s03_py]
173 # Make thicknesses and radii variable
174 Surface_1.ThicknessCell.MakeSolveVariable()
175 Surface_2.ThicknessCell.MakeSolveVariable()
176 Surface_2.RadiusCell.MakeSolveVariable()
177 Surface_3.ThicknessCell.MakeSolveVariable()
178 #! [e03s03_py]
179
180 #! [e03s04_py]
181 # Merit functions
182 TheMFE = TheSystem.MFE
183 Operand_1 = TheMFE.GetOperandAt(1)
184 Operand_1.ChangeType(ZOSAPI.Editors.MFE.MeritOperandType.ASTI)
185 Operand_1.Target = 0.0
186 Operand_1.Weight = 10.0
187 #! [e03s04_py]
188
189 Operand_2 = TheMFE.InsertNewOperandAt(2)
190 Operand_2.ChangeType(ZOSAPI.Editors.MFE.MeritOperandType.COMA)
191 Operand_2.Target = 0.0
192 Operand_2.Weight = 1.0
193
194 #Air min / max
195 Operand_3 = TheMFE.AddOperand()
196 Operand_3.ChangeType(ZOSAPI.Editors.MFE.MeritOperandType.MNCA)
197 Operand_3.Target = 0.5
198 Operand_3.Weight = 1.0
199 Operand_3.GetCellAt(2).IntegerValue = 1
200 Operand_3.GetCellAt(3).IntegerValue = 3
201 Operand_4 = TheMFE.AddOperand()
202 Operand_4.ChangeType(ZOSAPI.Editors.MFE.MeritOperandType.MXCA)
203 Operand_4.Target = 1000
204 Operand_4.Weight = 1.0
205 Operand_4.GetCellAt(2).IntegerValue = 1
206 Operand_4.GetCellAt(3).IntegerValue = 3
207 Operand_5 = TheMFE.AddOperand()
208 Operand_5.ChangeType(ZOSAPI.Editors.MFE.MeritOperandType.MNEA)
209 Operand_5.Target = 0.5
210 Operand_5.Weight = 1.0
211 Operand_5.GetCellAt(2).IntegerValue = 1
212 Operand_5.GetCellAt(3).IntegerValue = 3
213
214 # Material min / max
215 Operand_6 = TheMFE.AddOperand()
216 Operand_6.ChangeType(ZOSAPI.Editors.MFE.MeritOperandType.MNCG)
217 Operand_6.Target = 3.0
218 Operand_6.Weight = 1.0
219 Operand_6.GetCellAt(2).IntegerValue = 1
220 Operand_6.GetCellAt(3).IntegerValue = 3
221 Operand_7 = TheMFE.AddOperand()
222 Operand_7.ChangeType(ZOSAPI.Editors.MFE.MeritOperandType.MXCG)
223 Operand_7.Target = 15.0
224 Operand_7.Weight = 1.0
225 Operand_7.GetCellAt(2).IntegerValue = 1
226 Operand_7.GetCellAt(3).IntegerValue = 3
227 Operand_8 = TheMFE.AddOperand()
228 Operand_8.ChangeType(ZOSAPI.Editors.MFE.MeritOperandType.MNEG)
229 Operand_8.Target = 3.0
230 Operand_8.Weight = 1.0
231 Operand_8.GetCellAt(2).IntegerValue = 1
232 Operand_8.GetCellAt(3).IntegerValue = 3
233
234 #! [e03s05_py]
235 # Local optimisation till completion
236 print('Running Local Optimization')
237 LocalOpt = TheSystem.Tools.OpenLocalOptimization()
238 LocalOpt.Algorithm = ZOSAPI.Tools.Optimization.OptimizationAlgorithm.DampedLeastSquares
239 LocalOpt.Cycles = ZOSAPI.Tools.Optimization.OptimizationCycles.Automatic
240 LocalOpt.NumberOfCores = 8
241 LocalOpt.RunAndWaitForCompletion()
242 LocalOpt.Close()
243 #! [e03s05_py]
244
245 #! [e03s06_py]
246 # Hammer for 10 seconds
247 # need to 'import time' at the top of the file to use the pause function
248 print('Running Hammer Optimization')
249 HammerOpt = TheSystem.Tools.OpenHammerOptimization()
250 HammerOpt.RunAndWaitWithTimeout(10)
251 HammerOpt.Cancel()
252 HammerOpt.WaitForCompletion()
253 HammerOpt.Close()
254 #! [e03s06_py]
255
256 #Save and close
257 TheSystem.Save()
258
259 # This will clean up the connection to OpticStudio.
260 # Note that it closes down the server instance of OpticStudio, so you for maximum performance do not do
261 # this until you need to.
262 del zos
263 zos = None
Definition: ZemaxService.cs:198

Connect with Ansys