    

 ## On this page

  

 

 # PythonStandalone\_15\_Seq\_Optimization

 Last update: 17.07.2025 

 1import clr, os, winreg

 2from itertools import islice

 3 

 4import time

 5 

 6class PythonStandaloneApplication(object):

 7 class LicenseException(Exception):

 8 pass

 9 class ConnectionException(Exception):

 10 pass

 11 class InitializationException(Exception):

 12 pass

 13 class SystemNotPresentException(Exception):

 14 pass

 15 

 16 def __init__(self, path=None):

 17 \# determine location of ZOSAPI\_NetHelper.dll &amp; add as reference

 18 aKey = winreg.OpenKey(winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER), r"Software\\Zemax", 0, winreg.KEY_READ)

 19 zemaxData = winreg.QueryValueEx(aKey, 'ZemaxRoot')

 20 NetHelper = os.path.join(os.sep, zemaxData[0], r'ZOS-API\\Libraries\\ZOSAPI\_NetHelper.dll')

 21 winreg.CloseKey(aKey)

 22 clr.AddReference(NetHelper)

 23 import ZOSAPI_NetHelper

 24 

 25 \# Find the installed version of OpticStudio

 26 if path is None:

 27 isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize()

 28 else:

 29 \# Note -- uncomment the following line to use a custom initialization path

 30 isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize(path)

 31 

 32 \# determine the ZOS root directory

 33 if isInitialized:

 34 dir = ZOSAPI_NetHelper.ZOSAPI_Initializer.GetZemaxDirectory()

 35 else:

 36 raise PythonStandaloneApplication.InitializationException("Unable to locate Zemax OpticStudio. Try using a hard-coded path.")

 37 

 38 \# add ZOS-API referencecs

 39 clr.AddReference(os.path.join(os.sep, dir, "ZOSAPI.dll"))

 40 clr.AddReference(os.path.join(os.sep, dir, "ZOSAPI\_Interfaces.dll"))

 41 import ZOSAPI

 42 

 43 \# create a reference to the API namespace

 44 self.ZOSAPI = ZOSAPI

 45 

 46 \# create a reference to the API namespace

 47 self.ZOSAPI = ZOSAPI

 48 

 49 \# Create the initial connection class

 50 self.TheConnection = [ZOSAPI.ZOSAPI\_Connection](class_z_o_s_a_p_i_1_1_z_o_s_a_p_i___connection.xhtml)()

 51 

 52 if self.TheConnection is None:

 53 raise PythonStandaloneApplication.ConnectionException("Unable to initialize .NET connection to ZOSAPI")

 54 

 55 self.TheApplication = self.TheConnection.CreateNewApplication()

 56 if self.TheApplication is None:

 57 raise PythonStandaloneApplication.InitializationException("Unable to acquire ZOSAPI application")

 58 

 59 if self.TheApplication.IsValidLicenseForAPI == False:

 60 raise PythonStandaloneApplication.LicenseException("License is not valid for ZOSAPI use")

 61 

 62 self.TheSystem = self.TheApplication.PrimarySystem

 63 if self.TheSystem is None:

 64 raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")

 65 

 66 def __del__(self):

 67 if self.TheApplication is not None:

 68 self.TheApplication.CloseApplication()

 69 self.TheApplication = None

 70 

 71 self.TheConnection = None

 72 

 73 def OpenFile(self, filepath, saveIfNeeded):

 74 if self.TheSystem is None:

 75 raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")

 76 self.TheSystem.LoadFile(filepath, saveIfNeeded)

 77 

 78 def CloseFile(self, save):

 79 if self.TheSystem is None:

 80 raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")

 81 self.TheSystem.Close(save)

 82 

 83 def SamplesDir(self):

 84 if self.TheApplication is None:

 85 raise PythonStandaloneApplication.InitializationException("Unable to acquire ZOSAPI application")

 86 

 87 return self.TheApplication.SamplesDir

 88 

 89 def ExampleConstants(self):

 90 if self.TheApplication.LicenseStatus == self.ZOSAPI.LicenseStatusType.PremiumEdition:

 91 return "Premium"

 92 elif self.TheApplication.LicenseStatus == self.ZOSAPI.LicenseStatusTypeProfessionalEdition:

 93 return "Professional"

 94 elif self.TheApplication.LicenseStatus == self.ZOSAPI.LicenseStatusTypeStandardEdition:

 95 return "Standard"

 96 else:

 97 return "Invalid"

 98 

 99 def reshape(self, data, x, y, transpose = False):

 100 """Converts a System.Double\[,\] to a 2D list for plotting or post processing

 101 

 102 Parameters

 103 ----------

 104 data : System.Double\[,\] data directly from ZOS-API 

 105 x : x width of new 2D list [use var.GetLength(0) for dimension]

 106 y : y width of new 2D list [use var.GetLength(1) for dimension]

 107 transpose : transposes data; needed for some multi-dimensional line series data

 108 

 109 Returns

 110 -------

 111 res : 2D list; can be directly used with Matplotlib or converted to

 112 a numpy array using numpy.asarray(res)

 113 """

 114 if type(data) is not list:

 115 data = list(data)

 116 var_lst = [y] * x;

 117 it = iter(data)

 118 res = [list(islice(it, i)) for i in var_lst]

 119 if transpose:

 120 return self.transpose(res);

 121 return res

 122 

 123 def transpose(self, data):

 124 """Transposes a 2D list (Python3.x or greater). 

 125 

 126 Useful for converting mutli-dimensional line series (i.e. FFT PSF)

 127 

 128 Parameters

 129 ----------

 130 data : Python native list (if using System.Data[,] object reshape first) 

 131 

 132 Returns

 133 -------

 134 res : transposed 2D list

 135 """

 136 if type(data) is not list:

 137 data = list(data)

 138 return list(map(list, zip(*data)))

 139 

 140if __name__ == '\_\_main\_\_':

 141 zos = PythonStandaloneApplication()

 142 

 143 \# load local variables

 144 ZOSAPI = zos.ZOSAPI

 145 TheApplication = zos.TheApplication

 146 TheSystem = zos.TheSystem

 147 if not os.path.exists(TheApplication.SamplesDir + "\\\\API\\\\Python\\\\e15\_Seq\_Optimization"):

 148 os.makedirs(TheApplication.SamplesDir + "\\\\API\\\\Python\\\\e15\_Seq\_Optimization")

 149 

 150 \#! \[e15s01\_py\]

 151 \# Tests if file exists &amp; loads the correct double gauss design sample file

 152 if os.path.isfile(TheApplication.SamplesDir + '\\\\Short course\\\\sc\_dbga1.zos'):

 153 TheSystem.LoadFile(TheApplication.SamplesDir + '\\\\Short course\\\\sc\_dbga1.zos', False)

 154 else:

 155 TheSystem.LoadFile(TheApplication.SamplesDir + '\\\\Short course\\\\Optical System Design Using OpticStudio\\\\sc\_dbga1.zos', False)

 156 print('Double Gauss Design:')

 157 \#! \[e15s01\_py\]

 158 

 159 \#! \[e15s02\_py\]

 160 \# Define path locations

 161 SampleFile = TheApplication.SamplesDir + '\\\\API\\\\Python\\\\e15\_Seq\_Optimization\\\\OptimizedFile.zos'

 162 TheSystem.SaveAs(SampleFile)

 163 \#! \[e15s02\_py\]

 164 

 165 \#! \[e15s03\_py\]

 166 \# Define System Explorer

 167 \# Define Aperture

 168 SystExplorer = TheSystem.SystemData

 169 SystExplorer.Aperture.ApertureType = ZOSAPI.SystemData.ZemaxApertureType.EntrancePupilDiameter

 170 SystExplorer.Aperture.ApertureValue = 20

 171 \#! \[e15s03\_py\]

 172 

 173 \#! \[e15s04\_py\]

 174 \# Add 3 fields

 175 Field_1 = SystExplorer.Fields.GetField(1)

 176 NewField_2 = SystExplorer.Fields.AddField(0, 5.0, 1.0)

 177 SystExplorer.Fields.SetFieldType(ZOSAPI.SystemData.FieldType.ParaxialImageHeight)

 178 SystExplorer.Fields.MakeEqualAreaFields(3, 21.6)

 179 \#! \[e15s04\_py\]

 180 

 181 \#! \[e15s05\_py\]

 182 \# Add 3 wavelengths: F,d,C

 183 slPreset = SystExplorer.Wavelengths.SelectWavelengthPreset(ZOSAPI.SystemData.WavelengthPreset.FdC_Visible)

 184 \#! \[e15s05\_py\]

 185 

 186 \#! \[e15s06\_py\]

 187 \# Open a shaded model

 188 analysis = TheSystem.Analyses.New_Analysis(ZOSAPI.Analysis.AnalysisIDM.ShadedModel)

 189 analysis.Terminate()

 190 analysis.WaitForCompletion()

 191 analysisSettings = analysis.GetSettings()

 192 cfgFile = os.environ.get('Temp') + '\\\\sha.cfg'

 193 \# Save the current settings to the temp file

 194 analysisSettings.SaveTo(cfgFile)

 195 \# make your modifications to it

 196 \# MODIFYSETTINGS are defined in the ZPL help files: The Programming Tab &gt; About the ZPL &gt; Keywords

 197 analysisSettings.ModifySettings(cfgFile, 'SHA\_ROTX', '90')

 198 analysisSettings.ModifySettings(cfgFile, 'SHA\_ROTY', '0')

 199 analysisSettings.ModifySettings(cfgFile, 'SHA\_ROTZ', '0')

 200 \# now load in the modified settings

 201 analysisSettings.LoadFrom(cfgFile)

 202 \# If you want to overwrite your default CFG, copy it after you are done modifying the settings:

 203 \# CFG\_fullname = os.environ.get('USERPROFILE') + '\\\\Documents\\\\Zemax\\\\Configs\\\\POP.CFG'

 204 \# copyfile(cfgFile, CFG\_fullname)

 205 \# We don't need the temp file any more, so delete it

 206 if os.path.exists(cfgFile):

 207 os.remove(cfgFile)

 208 \# Run the analysis with the new settings

 209 analysis.ApplyAndWaitForCompletion()

 210 \#! \[e15s06\_py\]

 211 

 212 \#! \[e15s07\_py\]

 213 \# remove all variables and add a F# solve on last surface radius

 214 TheLDE = TheSystem.LDE

 215 \#IOpticalSystemTools

 216 tools = TheSystem.Tools

 217 tools.RemoveAllVariables()

 218 Surface_Last = TheLDE.GetSurfaceAt(TheLDE.NumberOfSurfaces - 2)

 219 Solver = Surface_Last.RadiusCell.CreateSolveType(ZOSAPI.Editors.SolveType.FNumber)

 220 Solver._S_FNumber.FNumber = 3.1415

 221 Surface_Last.RadiusCell.SetSolveData(Solver)

 222 SampleFile = TheApplication.SamplesDir + '\\\\API\\\\Python\\\\e15\_Seq\_Optimization\\\\OptimizedFile1.zos'

 223 TheSystem.SaveAs(SampleFile)

 224 \#! \[e15s07\_py\]

 225 

 226 \#! \[e15s08\_py\]

 227 \# change BFL &amp; run quick focus

 228 Surface_Last.Thickness = 40.0

 229 QFocus = tools.OpenQuickFocus()

 230 QFocus.Criterion = ZOSAPI.Tools.General.QuickAdjustCriterion.SpotSizeRadial

 231 QFocus.UseCentroid = True

 232 QFocus.RunAndWaitForCompletion()

 233 QFocus.Close()

 234 SampleFile = TheApplication.SamplesDir + '\\\\API\\\\Python\\\\e15\_Seq\_Optimization\\\\OptimizedFile2.zos'

 235 TheSystem.SaveAs(SampleFile)

 236 \#! \[e15s08\_py\]

 237 

 238 \#! \[e15s09\_py\]

 239 \# setup a few variables

 240 tools.SetAllRadiiVariable()

 241 Surface1 = TheLDE.GetSurfaceAt(1)

 242 Surface2 = TheLDE.GetSurfaceAt(2)

 243 Surface5 = TheLDE.GetSurfaceAt(5)

 244 Surface6 = TheLDE.GetSurfaceAt(6)

 245 Surface9 = TheLDE.GetSurfaceAt(9)

 246 Surface10 = TheLDE.GetSurfaceAt(10)

 247 Surface11 = TheLDE.GetSurfaceAt(11)

 248 \#! \[e15s09\_py\]

 249 

 250 \#! \[e15s10\_py\]

 251 \# Thickness 2, 5, 6, 9, and 11 variable

 252 Surface2.ThicknessCell.MakeSolveVariable()

 253 Surface5.ThicknessCell.MakeSolveVariable()

 254 Surface6.ThicknessCell.MakeSolveVariable()

 255 Surface9.ThicknessCell.MakeSolveVariable()

 256 Surface11.ThicknessCell.MakeSolveVariable()

 257 \#! \[e15s10\_py\]

 258 

 259 \#! \[e15s11\_py\]

 260 \# Thickness 10 pick up from 1

 261 Solver = Surface10.ThicknessCell.CreateSolveType(ZOSAPI.Editors.SolveType.SurfacePickup)

 262 SolverPickup = Solver._S_SurfacePickup

 263 SolverPickup.Surface = 1

 264 SolverPickup.ScaleFactor = 1

 265 SolverPickup.Column = ZOSAPI.Editors.LDE.SurfaceColumn.Thickness

 266 Surface10.ThicknessCell.SetSolveData(Solver)

 267 SampleFile = TheApplication.SamplesDir + '\\\\API\\\\Python\\\\e15\_Seq\_Optimization\\\\OptimizedFile3.zos'

 268 TheSystem.SaveAs(SampleFile)

 269 \#! \[e15s11\_py\]

 270 

 271 \#! \[e15s12\_py\]

 272 \# define merit function

 273 \# load merit function

 274 \# you need to have 64-bit pywin32 to use the SEQOptimizationWizard with an error

 275 TheMFE = TheSystem.MFE

 276 OptWizard = TheMFE.SEQOptimizationWizard

 277 

 278 \# Optimize for smallest RMS Spot, which is "Data" = 1

 279 OptWizard.Data = 1

 280 OptWizard.OverallWeight = 1

 281 \# Gaussian Quadrature with 3 rings (refers to index number = 2)

 282 OptWizard.Ring = 2

 283 \# Set air &amp; glass boundaries

 284 OptWizard.IsGlassUsed = True

 285 OptWizard.GlassMin = 3.0

 286 OptWizard.GlassMax = 15.0

 287 OptWizard.GlassEdge = 3.0

 288 OptWizard.IsAirUsed = True

 289 OptWizard.AirMin = 0.5

 290 OptWizard.AirMax = 1000.0

 291 OptWizard.AirEdge = 0.5

 292 \# And click OK!

 293 OptWizard.Apply()

 294 mf_filename = TheApplication.SamplesDir + '\\\\API\\\\Python\\\\e15\_Seq\_Optimization\\\\RMS\_Spot\_Radius.mf'

 295 TheMFE.SaveMeritFunction(mf_filename)

 296 TheMFE.LoadMeritFunction(mf_filename)

 297 SampleFile = TheApplication.SamplesDir + '\\\\API\\\\Python\\\\e15\_Seq\_Optimization\\\\OptimizedFile4.zos'

 298 TheSystem.SaveAs(SampleFile)

 299 \#! \[e15s12\_py\]

 300 

 301 \#! \[e15s13\_py\]

 302 \# Run local optimization and measure time

 303 \# Local optimization until completion

 304 t = time.time()

 305 

 306 LocalOpt = TheSystem.Tools.OpenLocalOptimization()

 307 if (LocalOpt != None):

 308 

 309 LocalOpt.Algorithm = ZOSAPI.Tools.Optimization.OptimizationAlgorithm.DampedLeastSquares

 310 LocalOpt.Cycles = ZOSAPI.Tools.Optimization.OptimizationCycles.Automatic

 311 LocalOpt.NumberOfCores = 8

 312 print('Local Optimization...')

 313 print('Initial Merit Function ', LocalOpt.InitialMeritFunction)

 314 

 315 LocalOpt.RunAndWaitForCompletion()

 316 print('Final Merit Function ', LocalOpt.CurrentMeritFunction)

 317 LocalOpt.Close()

 318 

 319 \# Get the elapsed time.

 320 elapsed = time.time() - t

 321 print('Time elapsed ' + str(round(elapsed,3)) + 's')

 322 \#! \[e15s13\_py\]

 323 

 324 \#! \[e15s14\_py\]

 325 \# run global search

 326 GlobalOptimTimeInSeconds = 5

 327 GlobalOpt = TheSystem.Tools.OpenGlobalOptimization()

 328 if (GlobalOpt != None):

 329 GlobalOpt.Algorithm = ZOSAPI.Tools.Optimization.OptimizationAlgorithm.DampedLeastSquares

 330 GlobalOpt.NumberOfCores = 8

 331 print('Global Optimization for ' + str(GlobalOptimTimeInSeconds) + ' seconds...')

 332 print('Initial Merit Function ', GlobalOpt.InitialMeritFunction)

 333 GlobalOpt.NumberToSave = ZOSAPI.Tools.Optimization.OptimizationSaveCount.Save_10

 334 

 335 GlobalOpt.RunAndWaitWithTimeout(1 * GlobalOptimTimeInSeconds)

 336 for j in range(1, 11):

 337 print(str(int(j)) + ': ' + str(GlobalOpt.CurrentMeritFunction(j)))

 338 GlobalOpt.Cancel()

 339 GlobalOpt.WaitForCompletion()

 340 GlobalOpt.Close()

 341 \#! \[e15s14\_py\]

 342 

 343 \#! \[e15s15\_py\]

 344 \# run hammer optimization

 345 HammerOptimTimeInSeconds = 5

 346 HammerOpt = TheSystem.Tools.OpenHammerOptimization()

 347 if (HammerOpt != None):

 348 HammerOpt.Algorithm = ZOSAPI.Tools.Optimization.OptimizationAlgorithm.DampedLeastSquares

 349 HammerOpt.NumberOfCores = 8

 350 print('Hammer Optimization for ' + str(HammerOptimTimeInSeconds) + ' seconds...')

 351 print('Initial Merit Function ', HammerOpt.InitialMeritFunction)

 352 

 353 HammerOpt.RunAndWaitWithTimeout(1 * HammerOptimTimeInSeconds)

 354 print('Final Merit Function ', HammerOpt.CurrentMeritFunction)

 355 

 356 HammerOpt.Cancel()

 357 HammerOpt.WaitForCompletion()

 358 HammerOpt.Close()

 359 \#! \[e15s15\_py\]

 360 

 361 TheSystem.Save()

 362 

 363 

 364 \# This will clean up the connection to OpticStudio.

 365 \# Note that it closes down the server instance of OpticStudio, so you for maximum performance do not do

 366 \# this until you need to.

 367 del zos

 368 zos = None

[ZOSAPI.ZOSAPI\_Connection](class_z_o_s_a_p_i_1_1_z_o_s_a_p_i___connection.xhtml)

**Definition:** ZemaxService.cs:198