/
zpcore.py
795 lines (617 loc) · 29.2 KB
/
zpcore.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
from __future__ import annotations
import locale
import logging
import warnings
import weakref
from os import PathLike
from typing import Literal
from semver.version import Version
from zospy.api import _ZOSAPI, constants
from zospy.api.apisupport import load_zosapi, load_zosapi_nethelper
from zospy.utils.pyutils import abspath
logger = logging.getLogger(__name__)
class OpticStudioSystem:
"""Wrapper for OpticStudio System instances."""
def __init__(self, zos_instance, system_instance):
"""Initiate the OpticStudioSystem.
Parameters
----------
zos_instance: ZOS
A ZOS instance
system_instance: ZOS.Application.PrimarySystem
A PrimarySystem instance obtained from the zos_instance.
"""
self._ZOS: ZOS = zos_instance
self._System: _ZOSAPI.IOpticalSystem = system_instance
self._OpenFile = None
@property
def SystemName(self) -> str:
"""Name of the current optical system."""
return self._System.SystemName
@SystemName.setter
def SystemName(self, value: str):
self._System.SystemName = value
@property
def SystemID(self) -> int:
"""Unique identifier for the optical system.
This identifier can be used to differentiate between multiple `OpticStudioSystem` instances.
Examples
--------
Create two different optical systems in a single instance of OpticStudio:
>>> import zospy as zp
>>> zos = zp.ZOS()
>>> oss1 = zos.connect_as_standalone(return_primary_system=True)
>>> oss2 = zos.create_new_system()
>>> oss1.SystemID != oss2.SystemID
True
"""
return self._System.SystemID
@property
def Mode(self) -> str:
"""Mode of the optical system. Either "Sequential" or "NonSequential"."""
return str(self._System.Mode)
@property
def SystemFile(self) -> str:
"""File path to the current optical system."""
return self._System.SystemFile
@property
def IsNonAxial(self) -> bool:
"""Indicates whether the optical system is axial and sequential.
`True` if the system is non-axial, `False` otherwise.
"""
return self._System.IsNonAxial
@property
def NeedsSave(self) -> bool:
"""Indicates if the optical system contains unsaved changes."""
return self._System.NeedsSave
@property
def SystemData(self) -> _ZOSAPI.SystemData.ISystemData:
"""Data for configuring everything in the system explorer.
Examples
--------
Change the aperture type to "FloatByStopSize":
>>> oss.SystemData.Aperture.ApertureType = zp.constants.SystemData.ZemaxApertureType.FloatByStopSize
Add a wavelength of 543 nm with weight 1:
>>> oss.SystemData.Wavelengths.AddWavelength(0.543, 1)
"""
return self._System.SystemData
@property
def LDE(self) -> _ZOSAPI.Editors.LDE.ILensDataEditor:
"""Lens Data Editor."""
return self._System.LDE
@property
def NCE(self) -> _ZOSAPI.Editors.NCE.INonSeqEditor:
"""Non-Sequential Component Editor."""
return self._System.NCE
@property
def MFE(self) -> _ZOSAPI.Editors.MFE.IMeritFunctionEditor:
"""Merit Function Editor."""
return self._System.MFE
@property
def TDE(self) -> _ZOSAPI.Editors.TDE.IToleranceDataEditor:
"""Tolerance Data Editor."""
return self._System.TDE
@property
def MCE(self) -> _ZOSAPI.Editors.MCE.IMultiConfigEditor:
"""Multi-Configuration Editor."""
return self._System.MCE
@property
def Analyses(self) -> _ZOSAPI.Analysis.I_Analyses:
"""Analyses for the current system."""
return self._System.Analyses
@property
def Tools(self) -> _ZOSAPI.Tools.IOpticalSystemTools:
"""Interface to run various tools on the optical system."""
return self._System.Tools
@property
def TheApplication(self) -> _ZOSAPI.IZOSAPI_Application:
"""Application in which the optical system is opened."""
return self._System.TheApplication
@property
def LensUpdateMode(self) -> str:
"""Lens update mode of the optical system.
Possible values are ['None', 'EditorsOnly', 'AllWindows'] or `zospy.constants.LensUpdateMode`.
"""
return str(self._System.UpdateMode)
@LensUpdateMode.setter
def LensUpdateMode(self, value: constants.LensUpdateMode | str):
self._System.UpdateMode = value
@property
def SessionModes(self) -> str:
"""Session mode of the optical system.
Possible values are ['FromPreferences', 'SessionOn', 'SessionOff'], or `zospy.constants.SessionModes`.
"""
return str(self._System.SessionMode)
@SessionModes.setter
def SessionModes(self, value: constants.SessionModes | str):
self._System.SessionMode = constants.process_constant(constants.SessionModes, value)
def get_current_status(self) -> str:
"""Get the last status of the optical system. If null or the length is 0, then the system has no errors.
Returns
-------
str
Current status of the optical system.
"""
return self._System.GetCurrentStatus()
def update_status(self) -> str:
"""Force an update of the system, and returns the current status.
Returns
-------
str
Current status of the optical system.
"""
return self._System.UpdateStatus()
def make_sequential(self) -> bool:
"""Set the optical system to sequential mode if it is not already."""
return self._System.MakeSequential()
def make_nonsequential(self) -> bool:
"""Set the optical system to non-sequential mode if it is not already."""
return self._System.MakeNonSequential()
def load(self, filepath: str | PathLike, saveifneeded: bool = False):
"""Load an earlier defined Zemax file.
Parameters
----------
filepath: str | PathLike
Path to the file that should be loaded
saveifneeded: bool
Defines if the current file is saved before opening the new file. Defaults to False.
"""
filepath = abspath(filepath)
logger.debug("Opening {} with SaveIfNeeded set to {}".format(filepath, saveifneeded))
self._System.LoadFile(filepath, saveifneeded)
self._OpenFile = filepath
logger.info("Opened {}".format(filepath))
def new(self, saveifneeded: bool = False):
"""Create a new session file.
Parameters
----------
saveifneeded: bool
Defines if the current file is saved before opening the new file. Defaults to False.
"""
logger.debug("Creating new file")
self._System.New(saveifneeded)
self._OpenFile = None
logger.info("Opened new file")
def save_as(self, filepath: str | PathLike):
"""Save the current session under a specified name.
Parameters
----------
filepath: str | PathLike
The filepath where the system should be saved. Note that a partial path or relative path does not work.
"""
filepath = abspath(filepath, check_directory_only=True)
logger.debug("Saving open session as {}".format(filepath))
self._System.SaveAs(filepath)
self._OpenFile = filepath
logger.info("File saved as {}".format(filepath))
def save(self) -> bool:
"""Save the current OpticStudio session.
If the file name for the current session is not known (e.g. when a new file was created), a warning is raised.
On these occurences, save_as() should be used once.
Returns (bool): A boolean indicating if the saving was successful.
"""
logger.debug("Saving file")
if self._OpenFile is None:
warnings.warn(
"The optical system has not been saved because no file name has been defined for the current system."
"Please use the 'save_as' function before using 'save'."
)
logger.critical("Could not save file because the path has not been set using save_as")
self._System.Save()
logger.info("File saved")
return True
def close(self, saveifneeded: bool = False) -> bool:
"""Close the optical system. Only works on secondary systems (See OpticStudio documentation).
Parameters
----------
saveifneeded : bool
Defines if the current file is saved before opening the new file. Defaults to False.
"""
return self._System.Close(saveifneeded)
def copy_system(self) -> OpticStudioSystem:
"""Copy the current OpticStudioSystem instance.
Returns
-------
zospy.zpcore.OpticStudioSystem
A ZOSPy OpticStudioSystem instance. Should be sequential.
"""
return OpticStudioSystem(self._ZOS, self._System.CopySystem())
def _ensure_correct_mode(self, required: str):
"""Ensure that the system is in the required type.
Parameters
----------
required: str
The required system type. Either 'Sequential' or 'NonSequential'.
Returns
-------
None
Raises
------
ValueError:
When the system is in the incorrect type
"""
logger.debug("Ensuring correct mode")
if self.Mode != required:
err = "Incorrect system type. System is in {} mode but {} mode is required".format(self.Mode, required)
logger.critical(err)
raise TypeError(err)
else:
logger.debug("System is in correct mode")
# ToDo: Eveluate what happens in 'mixed mode'
def __del__(self):
logger.debug("Closing connections with Zemax OpticStudio")
class ZOS:
"""A Communication instance for Zemax OpticStudio.
This class manages the connection between Python and Zemax OpticStudio through .NET, and controls OpticStudio
instances. Only one instance of `ZOS` can exist at any time.
Parameters
----------
preload : bool
A boolean indicating if nested namespaces should be preloaded upon initiating ZOS. Defaults to False.
zosapi_nethelper : str | None
Optional filepath to the ZOSAPI_NetHelper dll that is required to connect to OpticStudio. If None, the
Windows registry will be used to find the ZOSAPI_NetHelper dll. Defaults to `None`.
opticstudio_directory : str, optional
Path to the directory containing the OpticStudio DLLs. If `None`, the directory will be acquired through the
zosapi_nethelper. Note that either the zosapi_nethelper or the opticstudio_directory has to be specified,
not both.
Attributes
----------
ZOSAPI : None | netModuleObject
The ZOSAPI interface once loaded, else `None`.
ZOSAPI_NetHelper : None | netModuleObject
The ZOSAPI_NetHelper interface once loaded, else `None`.
Raises
------
ValueError
When it is attempted to initiate a second instance of `ZOS`. Only one instance can exist at any time.
Examples
--------
Preferred methods:
1. Connecting as extension:
Make sure OpticStudio is running and the "Interactive Extension" mode in the programming tab is active.
>>> import zospy as zp
>>> zos = zp.ZOS()
>>> oss = zos.connect(mode="extension")
2. Launching OpticStudio in standalone mode:
>>> import zospy as zp
>>> zos = zp.ZOS()
>>> oss = zos.connect(mode="standalone")
"""
_OpticStudioSystem = OpticStudioSystem
_instances = set()
def __new__(cls, *args, **kwargs):
if len(cls._instances) >= 1:
# As the number of applications within runtime is limited to 1 by Zemax, it is logical to also limit the
# number of ZOS instances
raise ValueError(
"Cannot have more than one active ZOS instance.\n\n"
"Since OpticStudio limits the number of connections to the ZOS-API to 1, only a single ZOS instance "
"is allowed. Re-use the existing instance, or delete the existing instance prior to initializing a "
"new one. See https://zospy.rtfd.io/faq#single-zos-instance for more information."
)
instance = super(ZOS, cls).__new__(cls)
return instance
def __init__(
self, preload: bool = False, zosapi_nethelper: str | None = None, opticstudio_directory: str | None = None
):
"""Initiation of the ZOS instance.
The ZOS instance can subsequently be used to connect to OpticStudio. See the examples in the class docstring for
more information.
Parameters
----------
preload : bool
A boolean indicating if nested namespaces should be preloaded upon initiating ZOS. Defaults to False.
zosapi_nethelper : str, optional
Path to the ZOSAPI_NetHelper dll that is required to connect to OpticStudio. If `None`, the
Windows registry will be used to find the ZOSAPI_NetHelper dll. Defaults to `None`.
opticstudio_directory : str, optional
Path to the directory containing the OpticStudio DLLs. If `None`, the directory will be acquired through the
zosapi_nethelper. Note that either the zosapi_nethelper or the opticstudio_directory has to be specified,
not both.
"""
logger.debug("Initializing ZOS instance")
self.ZOSAPI: _ZOSAPI = None
self.ZOSAPI_NetHelper = None
self.Connection: _ZOSAPI.IZOSAPI_Connection = None
self.Application: _ZOSAPI.IZOSAPI_Application = None
# Register the instance and create finalizers to tear down the ZOS instance when deleted
ZOS._instances.add(id(self))
weakref.finalize(self, ZOS.disconnect, self)
weakref.finalize(self, ZOS._instances.discard, id(self))
logger.info("ZOS instance initialized")
self._wakeup(preload=preload, zosapi_nethelper=zosapi_nethelper, opticstudio_directory=opticstudio_directory)
def _wakeup(self, preload: bool = False, zosapi_nethelper: str = None, opticstudio_directory: str | None = None):
"""Wake the ZOSAPI instance.
The parameters are passed to `ZOS._load_zos_dlls`.
Parameters
----------
preload : bool
A boolean indicating if nested namespaces should be preloaded.
zosapi_nethelper : str, optional
File path to the ZOSAPI_NetHelper dll, if `None`, the Windows registry will be used to find
ZOSAPI_NetHelper dll. Defaults to `None`.
opticstudio_directory : str, optional
Path to the directory containing the OpticStudio DLLs. If `None`, the directory will be acquired through the
zosapi_nethelper. Note that either the zosapi_nethelper or the opticstudio_directory has to be specified,
not both.
"""
if self.Connection is None:
self._load_zos_dlls(
preload=preload, zosapi_nethelper=zosapi_nethelper, opticstudio_directory=opticstudio_directory
)
self._assign_connection()
def wakeup(self, preload: bool = False, zosapi_nethelper: str = None):
"""Wake the ZOS-API.
.. deprecated:: 1.1.0
`wakeup` will be removed in ZOSPy 2.0.0, as it is automatically called by `__init__`.
The parameters are passed to self._load_zos_dlls().
Parameters
----------
preload : bool
A boolean indicating if nested namespaces should be preloaded.
zosapi_nethelper : str, optional
File path to the ZOSAPI_NetHelper dll, if None, the Windows registry will be used to find
ZOSAPI_NetHelper dll. Defaults to None.
"""
warnings.warn(
"ZOS.wakeup is deprecated and will be removed in ZOSPy 2.0.0. "
"It is now automatically called by __init__.",
DeprecationWarning,
)
self._wakeup(preload=preload, zosapi_nethelper=zosapi_nethelper)
def _load_zos_dlls(
self, preload: bool = False, zosapi_nethelper: str | None = None, opticstudio_directory: str | None = None
):
"""Load the ZOS-API DLLs and makes them available for usage through ZOS.ZOSAPI and ZOS.ZOSAPI_NetHelper.
As there are many nested namespaces in the ZOSAPI DLLs that are always available after import but not
preloaded, it can be chosen to do so. This should only be done for development reasons, as it likely slows
down the code.
If multiple versions of OpticStudio are installed on the same system, a specific version can be used by
manually specifying the path to the OpticStudio installation directory with `opticstudio_directory`.
Parameters
----------
preload: bool
A boolean indicating if nested namespaces should be preloaded.
zosapi_nethelper: str, optional
Path to the ZOSAPI_NetHelper dll, if `None`, the Windows registry will be used to find
ZOSAPI_NetHelper dll. Defaults to `None`.
opticstudio_directory : str, optional
Path to the directory containing the OpticStudio DLLs. If `None`, the directory will be acquired through the
zosapi_nethelper. Note that either the zosapi_nethelper or the opticstudio_directory has to be specified,
not both.
Raises
------
FileNotFoundError
An error occurred in locating one of the DLLs.
ModuleNotFoundError
One of the nested namespaces cannot be found. This error can only occur with preload set to True.
ValueError
Both `zosapi_nethelper` and `opticstudio_directory` are specified.
"""
if zosapi_nethelper is not None and opticstudio_directory is not None:
raise ValueError("Only one of `zosapi_nethelper` and `opticstudio_directory` may be specified.")
logger.debug("Loading ZOS DLLs with preload set to {}".format(preload))
if opticstudio_directory is not None:
self.ZOSAPI = load_zosapi(zemaxdirectory=opticstudio_directory, preload=preload)
else:
self.ZOSAPI_NetHelper = load_zosapi_nethelper(filepath=zosapi_nethelper, preload=preload)
self.ZOSAPI = load_zosapi(zosapi_nethelper=self.ZOSAPI_NetHelper, preload=preload)
def _assign_connection(self):
"""Assign the ZOSAPI Connection to self.Connection."""
if not self.Connection:
logger.debug("Assigning ZOSAPI_Connection() to self.Connection")
self.Connection = self.ZOSAPI.ZOSAPI_Connection()
else:
logger.debug("ZOSAPI_Connection() already assigned self.Connection")
def connect(
self,
mode: Literal["standalone", "extension"] = "standalone",
instance_number: int | None = None,
*,
message_logging: bool = True,
) -> OpticStudioSystem:
"""Connect to Zemax OpticStudio.
The application will be assigned to ZOS.Application.
Parameters
----------
mode : str
Connection mode, either "standalone" or "extension". Default is "standalone".
In standalone mode, ZOSPy initializes a new, invisible OpticStudio instance and connects to this instance.
In extension mode, ZOSPy connects to an already open instance of OpticStudio in "Interactive Extension"
mode.
instance_number : int, optional
An integer to specify the number of the instance used. Only applicable in extension mode.
message_logging : bool, optional
If `True`, OpticStudio's message logging will be enabled after establishing a connection.
Returns
-------
OpticStudioSystem
The primary optical system of the connected OpticStudio instance.
"""
if mode != "extension" and instance_number is not None:
warnings.warn("Instance number is only used in extension mode.")
self._assign_connection()
if self.Connection.IsAlive: # ToDo ensure no memory leak
raise RuntimeError("Only one Zemax application can exist within runtime")
if mode == "standalone":
self.Application = self.Connection.CreateNewApplication()
elif mode == "extension":
self.Application = self.Connection.ConnectAsExtension(instance_number or 0)
else:
raise ValueError(f"Invalid connection mode {mode}")
if not self.Application.IsValidLicenseForAPI:
logger.critical("OpticStudio Licence is not valid for API, connection not established")
raise ConnectionRefusedError("OpticStudio Licence is not valid for API, connection not established")
if message_logging:
self.Application.BeginMessageLogging()
return self.get_primary_system()
def connect_as_extension(
self, instancenumber: int = 0, return_primary_system: bool = False
) -> bool | OpticStudioSystem:
"""Connect to Zemax OpticStudio as extension.
.. deprecated:: 1.2.0
This method is deprecated and will be removed in ZOSPy 2.0.0. Use `ZOS.connect("extension")` instead.
The application will be assigned to ZOS.Application.
Parameters
----------
instancenumber : int, optional
An integer to specify the number of the instance used.
return_primary_system: bool, optional
A boolean indicating if the primary OpticStudioSystem should be returned. Defaults to `False`.
Returns
-------
bool | OpticStudioSystem
`True` if a valid connection is made, else `False`. If `return_primary_system` is `True`, the function
returns the primary `OpticStudioSystem`.
"""
warnings.warn("This method is deprecated, use 'ZOS.connect(\"extension\")' instead.", DeprecationWarning)
self._assign_connection()
if self.Connection.IsAlive: # ToDo ensure no memory leak
raise RuntimeError("Only one Zemax application can exist within runtime")
self.Application = self.Connection.ConnectAsExtension(instancenumber)
if not self.Application.IsValidLicenseForAPI:
logger.critical("OpticStudio Licence is not valid for API, connection not established")
if return_primary_system:
raise ConnectionRefusedError("OpticStudio Licence is not valid for API, connection not established")
return False
if return_primary_system:
return self.get_primary_system()
return True
def create_new_application(self, return_primary_system: bool = False) -> bool | OpticStudioSystem:
"""Create a standalone Zemax OpticStudio instance.
.. deprecated:: 1.2.0
This method is deprecated and will be removed in ZOSPy 2.0.0. Use `ZOS.connect()` instead.
The application will be assigned to ZOS.Application.
Parameters
----------
return_primary_system : bool, optional
A boolean indicating if the primary OpticStudioSystem should be returned. Defaults to `False`.
Returns
-------
bool | OpticStudioSystem
`True` if a valid connection is made, else `False`. If `return_primary_system` is `True`, the function
returns the primary `OpticStudioSystem`.
"""
warnings.warn("This method is deprecated, use 'ZOS.connect(\"standalone\")' instead.", DeprecationWarning)
self._assign_connection()
if self.Connection.IsAlive: # ToDo ensure no memory leak
raise RuntimeError("Only one Zemax application can exist within runtime")
self.Application = self.Connection.CreateNewApplication()
if not self.Application.IsValidLicenseForAPI:
logger.critical("OpticStudio Licence is not valid for API, connection not established")
if return_primary_system:
raise ConnectionRefusedError("OpticStudio Licence is not valid for API, connection not established")
return False
if return_primary_system:
return self.get_primary_system()
return True
def connect_as_standalone(self, return_primary_system: bool = False) -> bool | OpticStudioSystem:
"""Creates a standalone Zemax OpticStudio instance.
..deprecated:: 2.0.0
This method is deprecated and will be removed in ZOSPy 2.0.0. Use `ZOS.connect()` instead.
Equal to `ZOS.create_new_application`.
Parameters
----------
return_primary_system : bool, optional
A boolean indicating if the primary OpticStudioSystem should be returned. Defaults to `False`.
Returns
-------
bool | OpticStudioSystem
`True` if a valid connection is made, else `False`. If `return_primary_system` is `True`, the function
returns the primary `OpticStudioSystem`.
runs ZOS.get_primary_system() and directly returns OpticStudioSystem.
"""
return self.create_new_application(return_primary_system=return_primary_system)
def disconnect(self):
"""Disconnect from the connected OpticStudio instance.
When connected in standalone mode, this closes the standalone OpticStudio instance. When connected in extension
mode, this closes the connection but keeps the OpticStudio instance open.
"""
logger.debug("Disconnecting from OpticStudio")
if self.Application is not None:
self.Application.CloseApplication()
self.Application = None
logger.info("Disconnected from OpticStudio")
def create_new_system(self, system_mode: constants.SystemType | str = "Sequential") -> OpticStudioSystem:
"""Creates a new OpticStudioSystem. This works only if ZOSPy is connected to a standalone application.
Parameters
----------
system_mode : constants.SystemType | str
The mode of the new system, must be one of "Sequential", "NonSequential". Defaults to "Sequential".
Returns
-------
OpticStudioSystem
The new OpticStudioSystem.
"""
if self.Application.Mode == constants.ZOSAPI_Mode.Server:
new_system = self.Application.CreateNewSystem(constants.process_constant(constants.SystemType, system_mode))
return self._OpticStudioSystem(zos_instance=self, system_instance=new_system)
raise ValueError("Can only create a new system when using a standalone connection.")
def get_primary_system(self) -> OpticStudioSystem:
"""
Get the primary optical system.
Returns
-------
OpticStudioSystem
Primary optical system.
"""
optic_studio_system = self._OpticStudioSystem(zos_instance=self, system_instance=self.Application.PrimarySystem)
# Automatically populate _OpenFile when connecting in extension mode, to prevent unnecessary errors when
# calling save
if self.Application.Mode == constants.ZOSAPI_Mode.Plugin:
optic_studio_system._OpenFile = optic_studio_system.SystemFile
return optic_studio_system
def get_system(self, pos: int = 0) -> OpticStudioSystem:
"""
Get the optical system at the specified position.
Parameters
----------
pos : int
Index of the optical system. If `0`, the primary system is returned.
Returns
-------
OpticStudioSystem
Optical system at position `pos`.
"""
opticstudiosystem = self.Application.GetSystemAt(pos)
return self._OpticStudioSystem(zos_instance=self, system_instance=opticstudiosystem)
def get_txtfile_encoding(self) -> str:
"""Determines the encoding used to write textfiles in OpticStudio.
Returns
-------
str
The encoding used for textfiles by OpticStudio
Raises
------
RuntimeError
When ZOS does not have a connection to the OpticStudio application
NotImplementedError
When the ZOS.Application.Preferences.General.TXTFileEncoding is not one of ["Unicode", "ANSI"]
"""
if self.Application is None:
raise RuntimeError("ZOS.get_txtfile_encoding requires a live connection to the OpticStudio application.")
if str(self.Application.Preferences.General.TXTFileEncoding) == "Unicode":
return "UTF-16-le"
elif str(self.Application.Preferences.General.TXTFileEncoding) == "ANSI":
return locale.getpreferredencoding(do_setlocale=False)
else:
raise NotImplementedError(
f"ZOSPy cannot handle encoding {str(self.Application.Preferences.General.TXTFileEncoding)}"
)
def retrieve_logs(self) -> str:
"""Retrieve messages logged by OpticStudio.
Returns
-------
str
Messages logged by OpticStudio.
"""
return self.Application.RetrieveLogMessages()
@property
def version(self) -> Version:
"""Returns the OpticStudio version as Version object."""
return Version(
major=self.Application.ZOSMajorVersion,
minor=self.Application.ZOSMinorVersion,
patch=self.Application.ZOSSPVersion,
)