    

 ## On this page

  

 

 # PythonStandalone\_26\_modify\_opticstudio\_preferences

 Last update: 16.07.2025 

 1import clr, os, winreg

 2from itertools import islice

 3 

 4from System import Enum

 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 

 148 \#! \[e26s01\_py\]

 149 \# Define variables for OpticStudio Preferences

 150 Preference = TheApplication.Preferences

 151 PrefG = Preference.General

 152 Logic = ['False', 'True']

 153 

 154 \#Define the enums to a map/dictionary 

 155 DateTimeTypeLookup = {

 156 Enum.Parse(ZOSAPI.Preferences.DateTimeType, "None"):'None',

 157 ZOSAPI.Preferences.DateTimeType.DateTime:'DateTime', 

 158 ZOSAPI.Preferences.DateTimeType.Date:'Date'}

 159 LanguageLookup = {

 160 ZOSAPI.Preferences.LanguageType.Chinese:'Chinese', 

 161 ZOSAPI.Preferences.LanguageType.English:'English', 

 162 ZOSAPI.Preferences.LanguageType.Japanese:'Japanese'}

 163 EncodingTypeLookup= {

 164 ZOSAPI.Preferences.EncodingType.ANSI:'ANSI', 

 165 ZOSAPI.Preferences.EncodingType.Unicode:'Unicode'}

 166 \#! \[e26s01\_py\]

 167 

 168 \#! \[e26s02\_py\]

 169 \# Read and print the initial settings

 170 print('\\n===Check Settings===')

 171 print('DateTimeFormat: %s' %DateTimeTypeLookup[PrefG.DateTimeFormat])

 172 print('Language: %s' %LanguageLookup[PrefG.Language])

 173 print('ZMXFileEncoding: %s' %EncodingTypeLookup[PrefG.ZMXFileEncoding])

 174 print('TXTFileEncoding: %s' %EncodingTypeLookup[PrefG.TXTFileEncoding])

 175 print('UseSessionFiles: %s' %(Logic[PrefG.UseSessionFiles]))

 176 print('IncludeCalculatedDataInsession: %s' %(Logic[PrefG.IncludeCalculatedDataInSession]))

 177 print('UpdateMostRecentlyUsedList: %s' %(Logic[PrefG.UpdateMostRecentlyUsedList]))

 178 print('UserPreferences: %s' %(PrefG.UserPreferences))

 179 \#! \[e26s02\_py\]

 180 

 181 \#! \[e26s03\_py\]

 182 \# Reset the settings to default

 183 Preference.ResetToDefaults()

 184 \#! \[e26s03\_py\]

 185 

 186 \#! \[e26s04\_py\]

 187 \# Set the settings

 188 PrefG.DateTimeFormat = Enum.Parse(ZOSAPI.Preferences.DateTimeType, "None");

 189 PrefG.ZMXFileEncoding = ZOSAPI.Preferences.EncodingType.ANSI;

 190 PrefG.TXTFileEncoding = ZOSAPI.Preferences.EncodingType.ANSI;

 191 PrefG.UseSessionFiles = False;

 192 PrefG.IncludeCalculatedDataInSession = False;

 193 PrefG.UpdateMostRecentlyUsedList = False;

 194 PrefG.UserPreferences = 'Never gonna tell a lie and hurt you';

 195 \#! \[e26s04\_py\] 

 196 

 197 print('\\n===Final Settings===')

 198 print('DateTimeFormat: %s' %DateTimeTypeLookup[PrefG.DateTimeFormat])

 199 print('Language: %s' %LanguageLookup[PrefG.Language])

 200 print('ZMXFileEncoding: %s' %EncodingTypeLookup[PrefG.ZMXFileEncoding])

 201 print('TXTFileEncoding: %s' %EncodingTypeLookup[PrefG.TXTFileEncoding])

 202 print('UseSessionFiles: %s' %(Logic[PrefG.UseSessionFiles]))

 203 print('IncludeCalculatedDataInsession: %s' %(Logic[PrefG.IncludeCalculatedDataInSession]))

 204 print('UpdateMostRecentlyUsedList: %s' %(Logic[PrefG.UpdateMostRecentlyUsedList]))

 205 print('UserPreferences: %s' %(PrefG.UserPreferences))

 206 

 207 

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

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

 210 \# this until you need to.

 211 del zos

 212 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