    

 ## On this page

  

 

 # PythonStandalone\_06\_nsc\_phase

 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 &amp; 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](class_z_o_s_a_p_i_1_1_z_o_s_a_p_i___connection.xhtml)()

 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 """Converts a System.Double\[,\] to a 2D list for plotting or post processing

 102 

 103 Parameters

 104 ----------

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

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

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

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

 109 

 110 Returns

 111 -------

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

 113 a numpy array using numpy.asarray(res)

 114 """

 115 if type(data) is not list:

 116 data = list(data)

 117 var_lst = [y] * x;

 118 it = iter(data)

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

 120 if transpose:

 121 return self.transpose(res);

 122 return res

 123 

 124 def transpose(self, data):

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

 126 

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

 128 

 129 Parameters

 130 ----------

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

 132 

 133 Returns

 134 -------

 135 res : transposed 2D list

 136 """

 137 if type(data) is not list:

 138 data = list(data)

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

 140 

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

 142 zos = PythonStandaloneApplication()

 143 

 144 \# load local variables

 145 ZOSAPI = zos.ZOSAPI

 146 TheApplication = zos.TheApplication

 147 TheSystem = zos.TheSystem

 148 

 149 \# creates a new API directory

 150 if not os.path.exists(TheApplication.SamplesDir + "\\\\API\\\\Python"):

 151 os.makedirs(TheApplication.SamplesDir + "\\\\API\\\\Python")

 152 

 153 \#! \[e06s01\_py\]

 154 \# Create new non-sequential file

 155 TheSystem = TheApplication.CreateNewSystem(ZOSAPI.SystemType.NonSequential)

 156 TheNCE = TheSystem.NCE

 157 \#! \[e06s01\_py\]

 158 

 159 \#! \[e06s02\_py\]

 160 \# inserts objects and changes type

 161 TheNCE.InsertNewObjectAt(2)

 162 o1 = TheNCE.GetObjectAt(1)

 163 o2 = TheNCE.GetObjectAt(2)

 164 o1.ChangeType(o1.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.SourcePoint))

 165 o2.ChangeType(o2.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.DetectorRectangle))

 166 \#! \[e06s02\_py\]

 167 

 168 \#! \[e06s03\_py\]

 169 \# modify object's cell values in the NCE

 170 o1.ObjectData.NumberOfAnalysisRays = 1e6

 171 o1.ObjectData.NumberOfLayoutRays = 10

 172 o1.ObjectData.ConeAngle = 2.5

 173 

 174 o2.ZPosition = 1

 175 o2.ObjectData.XHalfWidth = 0.1

 176 o2.ObjectData.YHalfWidth = 0.1

 177 o2.ObjectData.NumberXPixels = 100

 178 o2.ObjectData.NumberYPixels = 100

 179 \#! \[e06s03\_py\]

 180 

 181 \#! \[e06s04\_py\]

 182 \# Setup and run the ray trace

 183 NSCRayTrace = TheSystem.Tools.OpenNSCRayTrace()

 184 NSCRayTrace.SplitNSCRays = False

 185 NSCRayTrace.ScatterNSCRays = True

 186 NSCRayTrace.UsePolarization = False

 187 NSCRayTrace.IgnoreErrors = True

 188 NSCRayTrace.SaveRays = False

 189 NSCRayTrace.ClearDetectors(0)

 190 

 191 NSCRayTrace.RunAndWaitForCompletion()

 192 NSCRayTrace.Close()

 193 \#! \[e06s04\_py\]

 194 

 195 plt.rcParams["figure.figsize"] = (12, 4)

 196 plt.set_cmap('jet')

 197 plt.subplot(1, 2, 1)

 198 det = 2

 199 

 200 \#! \[e06s05\_py\]

 201 \# extracts the irradiance data from detector

 202 rawData = TheSystem.NCE.GetAllDetectorDataSafe(det, 1)

 203 data = zos.reshape(rawData, rawData.GetLength(0), rawData.GetLength(1))

 204 \#data = (np.asarray(tuple(rawData))).reshape(rawData.GetLength(0), rawData.GetLength(1));

 205 irradiance = np.flipud(data);

 206 plt.imshow(irradiance)

 207 \#! \[e06s05\_py\]

 208 

 209 \# irradiance plot formatting

 210 plt.colorbar()

 211 plt.title('Incoherent Irradiance')

 212 plt.xticks([])

 213 plt.yticks([])

 214 

 215 plt.subplot(1, 2, 2)

 216 

 217 \#! \[e06s06\_py\]

 218 \# Calculates phase data from Er &amp; Ei

 219 rawData = TheSystem.NCE.GetAllCoherentDataSafe(det, ZOSAPI.Editors.NCE.DetectorDataType.Real);

 220 real = zos.reshape(rawData, rawData.GetLength(0), rawData.GetLength(1))

 221 \#real = (np.asarray(tuple(rawData))).reshape(rawData.GetLength(0), rawData.GetLength(1));

 222 rawData = TheSystem.NCE.GetAllCoherentDataSafe(det, ZOSAPI.Editors.NCE.DetectorDataType.Imaginary);

 223 imag = zos.reshape(rawData, rawData.GetLength(0), rawData.GetLength(1))

 224 \#imag = (np.asarray(tuple(rawData))).reshape(rawData.GetLength(0), rawData.GetLength(1));

 225 

 226 phase = np.flipud(np.arctan2(imag, real) * 180 / np.pi)

 227 plt.imshow(phase)

 228 \#! \[e06s06\_py\]

 229 

 230 \# phase plot formatting

 231 plt.colorbar()

 232 plt.title('Phase')

 233 plt.xticks([])

 234 plt.yticks([])

 235 

 236 TheSystem.SaveAs(TheApplication.SamplesDir + '\\\\API\\\\Python\\\\e06\_nsc\_phase.zos')

 237 

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

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

 240 \# this until you need to.

 241 del zos

 242 zos = None

 243 

 244 \# place plt.show() after clean up to release OpticStudio from memory

 245 plt.show()

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

**Definition:** ZemaxService.cs:198