    

 ## On this page

  

 

 # PythonStandalone\_17\_NSC\_BulkScatter

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

 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 if not os.path.exists(TheApplication.SamplesDir + "\\\\API\\\\Python"):

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

 147 

 148 \#! \[e17s01\_py\]

 149 \# Create New File

 150 TheSystem.New(False)

 151 TheSystem.MakeNonSequential()

 152 \#! \[e17s01\_py\]

 153 

 154 TheSystem.SystemData.MaterialCatalogs.AddCatalog('SCHOTT')

 155 

 156 \#! \[e17s02\_py\]

 157 \# Define Path Locations

 158 SamplesFolder = TheApplication.SamplesDir

 159 SampleFile = SamplesFolder + "\\\\API\\\\Python\\\\e17\_NSC\_BulkScatter.zos"

 160 TheSystem.SaveAs(SampleFile)

 161 \#! \[e17s02\_py\]

 162 

 163 \#! \[e17s03\_py\]

 164 \# Non-sequential component editor

 165 TheNCE = TheSystem.NCE

 166 Object_1 = TheNCE.InsertNewObjectAt(1)

 167 Object_2 = TheNCE.InsertNewObjectAt(2)

 168 Object_3 = TheNCE.GetObjectAt(3)

 169 \#! \[e17s03\_py\]

 170 

 171 \#! \[e17s04\_py\]

 172 \# Source point

 173 oType_1 = Object_1.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.SourcePoint)

 174 Object_1.ChangeType(oType_1)

 175 Source1_data = Object_1.ObjectData

 176 Source1_data.NumberOfLayoutRays = 3

 177 Source1_data.NumberOfAnalysisRays = 1000000

 178 \#! \[e17s04\_py\]

 179 

 180 \#! \[e17s05\_py\]

 181 \# Rectangular Volume

 182 \# Scattering Properties

 183 \# Draw:opacity set to 50%

 184 oType_2 = Object_2.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.RectangularVolume)

 185 Object_2.ChangeType(oType_2)

 186 Object_2.ZPosition = 2

 187 Object_2.Material = "N-BK7"

 188 RectVolume2_data = Object_2.ObjectData

 189 RectVolume2_data.X1HalfWidth = 12

 190 RectVolume2_data.Y1HalfWidth = 12

 191 RectVolume2_data.ZLength = 40

 192 RectVolume2_data.X2HalfWidth = 12

 193 RectVolume2_data.Y2HalfWidth = 12

 194 RectVolume2_volphysdata = Object_2.VolumePhysicsData

 195 RectVolume2_volphysdata.Model = ZOSAPI.Editors.NCE.VolumePhysicsModelType.AngleScattering

 196 RectVolume2_volphysdata.ModelSettings._S_AngleScattering.MeanPath = 5

 197 RectVolume2_volphysdata.ModelSettings._S_AngleScattering.Angle = 30

 198 RectVolume2_DrawData = Object_2.DrawData

 199 RectVolume2_DrawData.Opacity = ZOSAPI.Common.ZemaxOpacity.P50

 200 \#! \[e17s05\_py\]

 201 

 202 \#! \[e17s06\_py\]

 203 \# Detector Rectangle

 204 oType_3 = Object_3.GetObjectTypeSettings(ZOSAPI.Editors.NCE.ObjectType.DetectorRectangle)

 205 Object_3.RefObject = 2

 206 Object_3.ZPosition = 42

 207 Object_3.Material = "ABSORB"

 208 Object_3.ChangeType(oType_3)

 209 DetRect3_data = Object_3.ObjectData

 210 DetRect3_data.XHalfWidth = 15

 211 DetRect3_data.YHalfWidth = 15

 212 DetRect3_data.NumberXPixels = 25

 213 DetRect3_data.NumberYPixels = 25

 214 DetRect3_data.DataType = 0

 215 DetRect3_data.Color = 2

 216 DetRect3_data.Smoothing = 1

 217 \#! \[e17s06\_py\]

 218 

 219 \#! \[e17s07\_py\]

 220 \# Open a shaded model

 221 analysis = TheSystem.Analyses.New_Analysis(ZOSAPI.Analysis.AnalysisIDM.NSCShadedModel)

 222 analysis.WaitForCompletion()

 223 analysisSettings = analysis.GetSettings()

 224 cfgFile = SamplesFolder + "\\\\API\\\\Python\\\\e17\_NSC\_BulkScatter.cfg"

 225 analysisSettings.SaveTo(cfgFile) \# Save current settings to a cfg file

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

 227 analysisSettings.ModifySettings(cfgFile, "SHA\_ROTX", "20")

 228 analysisSettings.ModifySettings(cfgFile, "SHA\_ROTY", "-20")

 229 analysisSettings.ModifySettings(cfgFile, "SHA\_ROTZ", "30")

 230 analysisSettings.LoadFrom(cfgFile) \# Load in the newly modified settings

 231 \# If you want to overwrite your default CFG, save over it with newly modified CFG file:

 232 \# CFG\_fullname = "C:\\\\Users\\\\zachary.Derocher\\\\Documents\\\\Zemax\\\\Configs\\\\POP.CFG"

 233 \# import shutil

 234 \# shutil.copy(cfgFile, CFG\_fullname)

 235 analysis.ApplyAndWaitForCompletion() \# Run analysis

 236 \#! \[e17s07\_py\]

 237 

 238 \#! \[e17s08\_py\]

 239 \# Open a detector viewer

 240 det_analysis = TheSystem.Analyses.New_Analysis(ZOSAPI.Analysis.AnalysisIDM.DetectorViewer)

 241 det_analysisSettings = det_analysis.GetSettings()

 242 det_cfgFile = SamplesFolder + "\\\\API\\\\Python\\\\e17\_DetectorViewer.cfg"

 243 det_analysisSettings.SaveTo(det_cfgFile)

 244 det_analysisSettings.ModifySettings(det_cfgFile, "DVW\_SHOW", "2")

 245 det_analysisSettings.ModifySettings(det_cfgFile, "DVW\_SMOOTHING", "1")

 246 det_analysisSettings.LoadFrom(det_cfgFile)

 247 det_analysis.ApplyAndWaitForCompletion()

 248 \#! \[e17s08\_py\]

 249 

 250 \#! \[e17s09\_py\]

 251 \# Run a ray trace

 252 NSCRayTrace = TheSystem.Tools.OpenNSCRayTrace()

 253 NSCRayTrace.SplitNSCRays = False

 254 NSCRayTrace.ScatterNSCRays = True

 255 NSCRayTrace.UsePolarization = False

 256 NSCRayTrace.IgnoreErrors = True

 257 NSCRayTrace.SaveRays = False

 258 NSCRayTrace.ClearDetectors(0)

 259 NSCRayTrace.RunAndWaitForCompletion()

 260 NSCRayTrace.Close()

 261 \#! \[e17s09\_py\]

 262 

 263 TheSystem.SaveAs(SampleFile)

 264 print("Saved 'NSC\_BulkScatter.zos' file")

 265 

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

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

 268 \# this until you need to.

 269 del zos

 270 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