-
Notifications
You must be signed in to change notification settings - Fork 64
/
zdde.py
12393 lines (10969 loc) · 480 KB
/
zdde.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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: zdde.py
# Purpose: Python based DDE link with ZEMAX server, similar to Matlab based
# MZDDE toolbox.
# Licence: MIT License
# This file is subject to the terms and conditions of the MIT License.
# For further details, please refer to LICENSE.txt
# Revision: 2.0.3
#-------------------------------------------------------------------------------
"""PyZDDE, which is a toolbox written in Python, is used for communicating
with ZEMAX using the Microsoft's Dynamic Data Exchange (DDE) messaging
protocol. The docstring examples in the functions assume that PyZDDE is
imported as ``import pyzdde.zdde as pyz`` and a PyZDDE communication object
is then created as ``ln = pyz.createLink()`` or ``ln = pyz.PyZDDE();
ln.zDDEInit()``.
"""
from __future__ import division
from __future__ import print_function
import sys as _sys
#import struct as _struct
import os as _os
import collections as _co
import subprocess as _subprocess
import math as _math
import time as _time
import datetime as _datetime
import re as _re
import shutil as _shutil
import warnings as _warnings
import codecs as _codecs
# Try to import IPython if it is available (for notebook helper functions)
try:
from IPython.core.display import display as _display
from IPython.core.display import Image as _Image
except ImportError:
_global_IPLoad = False
else:
_global_IPLoad = True
# Determine if in IPython Environment
try: # get_ipython() method is not available in IPython versions prior to 2.0
from IPython import get_ipython as _get_ipython
except:
_global_in_IPython_env = False
else:
if _get_ipython(): # if global interactive shell instance is available
_global_in_IPython_env = True
else:
_global_in_IPython_env = False
# Try to import Matplotlib's imread
try:
import matplotlib.image as _matimg
except ImportError:
_global_mpl_img_load = False
else:
_global_mpl_img_load = True
# The first module to import that is not one of the standard modules MUST
# be the config module as it sets up the different global and settings variables
_currDir = _os.path.dirname(_os.path.realpath(__file__))
_pDir = _os.path.split(_currDir)[0]
settings_file = _os.path.join(_currDir, "settings.ini")
if not _os.path.isfile(settings_file):
src = _os.path.join(_currDir, "settings.ini-dist")
_shutil.copy(src, settings_file)
import pyzdde.config as _config
_global_pyver3 = _config._global_pyver3
_global_use_unicode_text = _config._global_use_unicode_text
imageMagickSettings = _config.getImageMagickSettings()
_global_use_installed_imageMagick = imageMagickSettings[0]
_global_imageMagick_dir = imageMagickSettings[1]
# DDEML communication module
_global_ddeclient_load = False # True if module could be loaded.
try:
import pyzdde.ddeclient as _dde
_global_ddeclient_load = True
except ImportError:
# System may not be windows; only provide functions that do not use zemax
print("DDE client couldn't be loaded. All functions prefixed with"
" \"z\" or \"ipz\" may not work.")
# Python 2/ Python 3 differential imports
if _global_pyver3:
_izip = zip
_imap = map
xrange = range
import tkinter as _tk
import tkinter.messagebox as _MessageBox
else:
from itertools import izip as _izip, imap as _imap
import Tkinter as _tk
import tkMessageBox as _MessageBox
# Pyzdde local module imports
import pyzdde.zcodes.zemaxbuttons as zb
import pyzdde.zcodes.zemaxoperands as zo
import pyzdde.utils.pyzddeutils as _putils
import pyzdde.zfileutils as _zfu
#%% Constants
_DEBUG_PRINT_LEVEL = 0 # 0 = No debug prints, but allow all essential prints
# 1 to 2 levels of debug print, 2 = print all
_MAX_PARALLEL_CONV = 2 # Max no of simul. conversations possible with Zemax
_system_aperture = {0 : 'EPD',
1 : 'Image space F/#',
2 : 'Object space NA',
3 : 'Float by stop',
4 : 'Paraxial working F/#',
5 : 'Object cone angle'}
macheps = _sys.float_info.epsilon # machine epsilon
#%% Helper function for debugging
def _debugPrint(level, msg):
"""Internal helper function to print debug messages
Parameters
----------
level : integer (0, 1 or 2)
0 = message will definitely be printed;
1 or 2 = message will be printed if ``level >= _DEBUG_PRINT_LEVEL``.
msg : string
message to print
"""
global _DEBUG_PRINT_LEVEL
if level <= _DEBUG_PRINT_LEVEL:
print("DEBUG PRINT, module - zdde (Level " + str(level)+ "): " + msg)
#%% Module methods
# bind functions from utils module
cropImgBorders = _putils.cropImgBorders
imshow = _putils.imshow
# bind functions from zemax buttons module
findZButtonCode = zb.findZButtonCode
getZButtonCount = zb.getZButtonCount
isZButtonCode = zb.isZButtonCode
showZButtonList = zb.showZButtonList
showZButtonDescription = zb.showZButtonDescription
# bind functions from zemax operand module
findZOperand = zo.findZOperand
getZOperandCount = zo.getZOperandCount
isZOperand = zo.isZOperand
showZOperandList = zo.showZOperandList
showZOperandDescription = zo.showZOperandDescription
# decorator for automatically push and refresh to and from LDE (Experimental)
def autopushandrefresh(func):
def wrapped(self, *args, **kwargs):
if self.apr: # if automatic push refresh is True
if (args[0].startswith('Get') or
args[0].startswith('Set') or
args[0].startswith('Insert') or
args[0].startswith('Delete')):
self._conversation.Request('GetRefresh')
reply = func(self, *args, **kwargs)
if (args[0].startswith('Set') or
args[0].startswith('Insert') or
args[0].startswith('Delete')):
self._conversation.Request('PushLens,1')
else:
reply = func(self, *args, **kwargs)
return reply
return wrapped
_global_dde_linkObj = {}
def createLink(apr=False):
"""Create a DDE communication link with Zemax
Usage: ``import pyzdde.zdde as pyz; ln = pyz.createLink()``
Helper function to create, initialize and return a PyZDDE communication
object.
Parameters
----------
apr : bool
if `True`, automatically push and refresh lens to and from LDE to DDE
Returns
-------
link : object
a PyZDDE communication object if successful, else ``None``.
Notes
-----
1. This module level method may used instead of \
``ln = pyz.PyZDDE(); ln.zDDEInit()``.
2. Zemax application must be running.
See Also
--------
closeLink(), zDDEInit()
"""
global _global_dde_linkObj
global _MAX_PARALLEL_CONV
dlen = len(_global_dde_linkObj)
if dlen < _MAX_PARALLEL_CONV:
link = PyZDDE(apr=apr)
status = link.zDDEInit()
if not status:
_global_dde_linkObj[link] = link._appName # This can be something more useful later
_debugPrint(1,"Link created. Link Dict = {}".format(_global_dde_linkObj))
return link
else:
print("Could not initiate instance.")
return None
else:
print("Link not created. Reached maximum allowable live link of ",
_MAX_PARALLEL_CONV)
return None
def closeLink(link=None):
"""Close DDE communication link with Zemax
Usage: ``pyz.closeLink([ln])``
Helper function, for closing DDE communication.
Parameters
----------
link : PyZDDE link object, optional
If a specific link object is not given, all existing links are
closed.
Returns
-------
None
See Also
--------
zDDEClose() :
PyZDDE instance method to close a link.
Use this method (as ``ln.zDDEClose()``) if the link was created as \
``ln = pyz.PyZDDE(); ln.zDDEInit()``
close() :
Another instance method to close a link for easy typing.
Use this method (as ``ln.close()``) or ``pyz.closeLink(ln)`` if the \
link was created as ``ln = pyz.createLink()``
"""
global _global_dde_linkObj
dde_closedLinkObj = []
if link:
link.zDDEClose()
dde_closedLinkObj.append(link)
else:
for link in _global_dde_linkObj:
link.zDDEClose()
dde_closedLinkObj.append(link)
for item in dde_closedLinkObj:
_global_dde_linkObj.pop(item)
def setTextEncoding(txt_encoding=0):
"""Sets PyZDDE text encoding to match the TXT encoding in Zemax
Usage: ``pyz.setTextEncoding([txt_encoding])``
Parameters
----------
txt_encoding : integer (0 or 1)
0 = ASCII; 1 = UNICODE
Returns
-------
status : string
current setting (& information if the setting was changed or not)
Notes
-----
Not required to set the encoding for every new session as PyZDDE stores
the setting.
See Also
--------
getTextEncoding()
"""
global _global_use_unicode_text
if _global_use_unicode_text and txt_encoding:
print('TXT encoding is UNICODE; no change required')
elif not _global_use_unicode_text and not txt_encoding:
print('TXT encoding is ASCII; no change required')
elif not _global_use_unicode_text and txt_encoding:
if _config.setTextEncoding(txt_encoding=1):
_global_use_unicode_text = True
print('Successfully changed to UNICODE')
else:
print("ERROR: Couldn't change settings")
elif _global_use_unicode_text and not txt_encoding:
if _config.setTextEncoding(txt_encoding=0):
_global_use_unicode_text = False
print('Successfully changed to ASCII')
else:
print("ERROR: Couldn't change settings")
def getTextEncoding():
"""Returns the current text encoding set in PyZDDE
Usage: ``pyz.getTextEncoding()``
Parameters
----------
None
Returns
-------
encoding : string
'ascii' or 'unicode'
See Also
--------
setTextEncoding
"""
return _config.getTextEncoding()
def setImageMagickSettings(use_installed_ImageMagick, imageMagick_dir=None):
"""Set the use-flag and imageMagick installation directory settings
Parameters
----------
use_installed_ImageMagick : bool
boolean flag to indicate whether to use installed version
of ImageMagick (``True``) or not (``False``)
imageMagick_dir : string, optional
full path to the installation directory. For example:
``C:\\Program Files\\ImageMagick-6.8.9-Q8``
Returns
-------
imageMagick_settings : tuple
updated imageMagick settings
"""
global _global_use_installed_imageMagick
global _global_imageMagick_dir
if not isinstance(use_installed_ImageMagick, bool):
raise ValueError("Expecting bool")
if imageMagick_dir and not _os.path.isdir(imageMagick_dir):
raise ValueError("Expecting valid directory or None")
if imageMagick_dir and not _os.path.isfile(_os.path.join(imageMagick_dir,
'convert.exe')):
raise ValueError("Couldn't find program convert.exe in the path!")
_config.setImageMagickSettings(use_installed_ImageMagick, imageMagick_dir)
imageMagickSettings = _config.getImageMagickSettings()
_global_use_installed_imageMagick = imageMagickSettings[0]
_global_imageMagick_dir = imageMagickSettings[1]
return (_global_use_installed_imageMagick, _global_imageMagick_dir)
def getImageMagickSettings():
"""Return the use-flag and imageMagick installation directory settings
Parameters
----------
None
Returns
-------
use_flag : bool
if ``True``, then PyZDDE uses the installed version of ImageMagick
software. If ``False``, then the version of ImageMagick that comes
with PyZDDE will be used.
imageMagick_dir : string
ImageMagick installation directory.
"""
return _config.getImageMagickSettings()
# PyZDDE class' utility function (for internal use)
def _createAppNameDict(maxElements):
"""Internal function to create a pool (dictionary) of possible app-names
Parameters
----------
maxElements : integer
maximum elements in the dictionary
Returns
-------
appNameDict : dictionary
dictionary of app-names (keys) with values, set to False, indicating
name hasn't been taken.
"""
appNameDict = {}
appNameDict['ZEMAX'] = False
for i in range(1, maxElements):
appNameDict['ZEMAX'+str(i)] = False
return appNameDict
def _getAppName(appNameDict):
"""Return available name from the pool of app-names.
"""
if not appNameDict['ZEMAX']:
appNameDict['ZEMAX'] = True
return 'ZEMAX'
else:
k_available = None
for k, v in appNameDict.items():
if not v:
k_available = k
break
if k_available:
appNameDict[k_available] = True
return k_available
else:
return None
#%% PyZDDE class
class PyZDDE(object):
"""PyZDDE class for communicating with Zemax
There are two ways of instantiating and initiating a PyZDDE object:
1. Instantiate using ``ln = pyz.PyZDDE()`` and then initiate \
using ``ln.zDDEInit()`` or
2. ``pyz.createLink()`` instantiates & initiates a PyZDDE object & \
returns (recommended way)
"""
__chNum = 0 # channel Number; there is no restriction on number of ch
__liveCh = 0 # no. of live/ simul channels; Can't be > _MAX_PARALLEL_CONV
__server = 0
__appNameDict = _createAppNameDict(_MAX_PARALLEL_CONV) # {'ZEMAX': False, 'ZEMAX1': False}
version = '2.0.3'
# Other class variables
# Surface data codes for getting and setting surface data
SDAT_TYPE = 0 # Surface type name
SDAT_COMMENT = 1 # Comment
SDAT_CURV = 2 # Curvature
SDAT_THICK = 3 # Thickness
SDAT_GLASS = 4 # Glass
SDAT_SEMIDIA = 5 # Semi-Diameter
SDAT_CONIC = 6 # Conic
SDAT_COAT = 7 # Coating
SDAT_TCE = 8 # Thermal Coefficient of Expansion (TCE)
SDAT_UD_DLL = 9 # User-defined DLL
SDAT_IGNORE_S_FLAG = 20 # Ignore surface flag
SDAT_TILT_DCNTR_ORD_BEFORE = 51 # Before tilt and decenter order
SDAT_DCNTR_X_BEFORE = 52 # Before decenter x
SDAT_DCNTR_Y_BEFORE = 53 # Before decenter y
SDAT_TILT_X_BEFORE = 54 # Before tilt x
SDAT_TILT_Y_BEFORE = 55 # Before tilt y
SDAT_TILT_Z_BEFORE = 56 # Before tilt z
SDAT_TILT_DCNTR_STAT_AFTER = 60 # After status
SDAT_TILT_DCNTR_ORD_AFTER = 61 # After tilt and decenter order
SDAT_DCNTR_X_AFTER = 62 # After decenter x
SDAT_DCNTR_Y_AFTER = 63 # After decenter y
SDAT_TILT_X_AFTER = 64 # After tilt x
SDAT_TILT_Y_AFTER = 65 # After tilt y
SDAT_TILT_Z_AFTER = 66 # After tilt z
SDAT_USE_LAYER_MULTI_INDEX = 70 # Use Layer multipliers and index offsets
SDAT_LAYER_MULTI_VAL = 71 # Layer multiplier value
SDAT_LAYER_MULTI_STAT = 72 # Layer multiplier status
SDAT_LAYER_INDEX_OFFSET_VAL = 73 # Layer index offset value
SDAT_LAYER_INDEX_OFFSET_STAT = 74 # Layer index offset status
SDAT_LAYER_EXTINCT_OFFSET_VAL = 75 # Layer extinction offset value
SDAT_LAYER_EXTINCT_OFFSET_STAT = 76 # Layer extinction offset status
# Surface parameter codes for getting and setting solves
SOLVE_SPAR_CURV = 0 # Curvature
SOLVE_SPAR_THICK = 1 # Thickness
SOLVE_SPAR_GLASS = 2 # Glass
SOLVE_SPAR_SEMIDIA = 3 # Semi-Diameter
SOLVE_SPAR_CONIC = 4 # Conic
SOLVE_SPAR_PAR0 = 17 # Parameter 0
SOLVE_SPAR_PAR1 = 5 # Parameter 1
SOLVE_SPAR_PAR2 = 6 # Parameter 2
SOLVE_SPAR_PAR3 = 7 # Parameter 3
SOLVE_SPAR_PAR4 = 8 # Parameter 4
SOLVE_SPAR_PAR5 = 9 # Parameter 5
SOLVE_SPAR_PAR6 = 10 # Parameter 6
SOLVE_SPAR_PAR7 = 11 # Parameter 7
SOLVE_SPAR_PAR8 = 12 # Parameter 8
SOLVE_SPAR_PAR9 = 13 # Parameter 9
SOLVE_SPAR_PAR10 = 14 # Parameter 10
SOLVE_SPAR_PAR11 = 15 # Parameter 11
SOLVE_SPAR_PAR12 = 16 # Parameter 12
# Solve type code for use with get/set solve function
SOLVE_CURV_FIXED = 0 # Solve on curvature; fixed
SOLVE_CURV_VAR = 1 # Solve on curvature; variable (V)
SOLVE_CURV_MR_ANG = 2 # Solve on curvature; marginal ray angle (M)
SOLVE_CURV_CR_ANG = 3 # Solve on curvature; chief ray angle (C)
SOLVE_CURV_PICKUP = 4 # Solve on curvature; pickup (P)
SOLVE_CURV_MR_NORM = 5 # Solve on curvature; marginal ray normal (N)
SOLVE_CURV_CR_NORM = 6 # Solve on curvature; chief ray normal (N)
SOLVE_CURV_APLAN = 7 # Solve on curvature; aplanatic (A)
SOLVE_CURV_ELE_POWER = 8 # Solve on curvature; element power (X)
SOLVE_CURV_CON_SURF = 9 # Solve on curvature; concentric with surface (S)
SOLVE_CURV_CON_RADIUS = 10 # Solve on curvature; concentric with radius (R)
SOLVE_CURV_FNUM = 11 # Solve on curvature; f/# (F)
SOLVE_CURV_ZPL = 12 # Solve on curvature; zpl macro (Z)
SOLVE_THICK_FIXED = 0 # Solve on thickness; fixed
SOLVE_THICK_VAR = 1 # Solve on thickness; variable (V)
SOLVE_THICK_MR_HGT = 2 # Solve on thickness; marginal ray height (M)
SOLVE_THICK_CR_HGT = 3 # Solve on thickness; chief ray height (C)
SOLVE_THICK_EDGE_THICK = 4 # Solve on thickness; edge thickness (E)
SOLVE_THICK_PICKUP = 5 # Solve on thickness; pickup (P)
SOLVE_THICK_OPD = 6 # Solve on thickness; optical path difference (O)
SOLVE_THICK_POS = 7 # Solve on thickness; position (T)
SOLVE_THICK_COMPENSATE = 8 # Solve on thickness; compensator (S)
SOLVE_THICK_CNTR_CURV = 9 # Solve on thickness; center of curvature (X)
SOLVE_THICK_PUPIL_POS = 10 # Solve on thickness; pupil position (U)
SOLVE_THICK_ZPL = 11 # Solve on thickness; zpl macro (Z)
SOLVE_GLASS_FIXED = 0 # Solve on glass; fixed
SOLVE_GLASS_MODEL = 1 # Solve on glass; model
SOLVE_GLASS_PICKUP = 2 # Solve on glass; pickup (P)
SOLVE_GLASS_SUBS = 3 # Solve on glass; substitute (S)
SOLVE_GLASS_OFFSET = 4 # Solve on glass; offset (O)
SOLVE_SEMIDIA_AUTO = 0 # Solve on semi-diameter; automatic
SOLVE_SEMIDIA_FIXED = 1 # Solve on semi-diameter; fixed (U)
SOLVE_SEMIDIA_PICKUP = 2 # Solve on semi-diameter; pickup (P)
SOLVE_SEMIDIA_MAX = 3 # Solve on semi-diameter; maximum (M)
SOLVE_SEMIDIA_ZPL = 4 # Solve on semi-diameter; zpl macro (Z)
SOLVE_CONIC_FIXED = 0 # Solve on conic; fixed
SOLVE_CONIC_VAR = 1 # Solve on conic; variable (V)
SOLVE_CONIC_PICKUP = 2 # Solve on conic; pickup (P)
SOLVE_CONIC_ZPL = 3 # Solve on conic; zpl macro (Z)
SOLVE_PAR0_FIXED = 0 # Solve on parameter 0; fixed
SOLVE_PAR0_VAR = 1 # Solve on parameter 0; variable (V)
SOLVE_PAR0_PICKUP = 2 # Solve on parameter 0; pickup (P)
SOLVE_PARn_FIXED = 0 # Solve on parameter n (b/w 1 - 12); fixed
SOLVE_PARn_VAR = 1 # Solve on parameter n (b/w 1 - 12); variable (V)
SOLVE_PARn_PICKUP = 2 # Solve on parameter n (b/w 1 - 12); pickup (P)
SOLVE_PARn_CR = 3 # Solve on parameter n (b/w 1 - 12); chief-ray (C)
SOLVE_PARn_ZPL = 4 # Solve on parameter n (b/w 1 - 12); zpl macro (Z)
SOLVE_EDATA_FIXED = 0 # Solve on extra data values; fixed
SOLVE_EDATA_VAR = 1 # Solve on extra data values; variable (V)
SOLVE_EDATA_PICKUP = 2 # Solve on extra data values; pickup (P)
SOLVE_EDATA_ZPL = 3 # Solve on extra data values; zpl macro (Z)
# Object parameter codes for NSC solve
NSCSOLVE_OPAR_XPOS = -1
NSCSOLVE_OPAR_YPOS = -2
NSCSOLVE_OPAR_ZPOS = -3
NSCSOLVE_OPAR_XTILT = -4
NSCSOLVE_OPAR_YTILT = -5
NSCSOLVE_OPAR_ZTILT = -6
ANA_POP_SAMPLE_32 = 1
# Sampling codes for POP analysis
ANA_POP_SAMPLE_64 = 2
ANA_POP_SAMPLE_128 = 3
ANA_POP_SAMPLE_256 = 4
ANA_POP_SAMPLE_512 = 5
ANA_POP_SAMPLE_1024 = 6
ANA_POP_SAMPLE_2048 = 7
ANA_POP_SAMPLE_4096 = 8
ANA_POP_SAMPLE_8192 = 9
ANA_POP_SAMPLE_16384 = 10
# Sampling codes for PSF/MTF analysis
ANA_PSF_SAMPLE_32x32 = 1
ANA_PSF_SAMPLE_64x64 = 2
ANA_PSF_SAMPLE_128x128 = 3
ANA_PSF_SAMPLE_256x256 = 4
ANA_PSF_SAMPLE_512x512 = 5
ANA_PSF_SAMPLE_1024x1024 = 6
ANA_PSF_SAMPLE_2048x2048 = 7
ANA_PSF_SAMPLE_4096x4096 = 8
ANA_PSF_SAMPLE_8192x8192 = 9
ANA_PSF_SAMPLE_16384x16384 = 10
def __init__(self, apr=False):
"""Creates an instance of PyZDDE class
Usage: ``ln = pyz.PyZDDE()``
Parameters
----------
apr : bool
if `True`, automatically push and refresh lens to and from LDE to DDE
Returns
-------
ln : PyZDDE object
Notes
-----
1. Following the creation of PyZDDE object, initiate the
communication channel as ``ln.zDDEInit()``
2. Consider using the module level function ``pyz.createLink()`` to
create and initiate a DDE channel instead of ``ln = pyz.PyZDDE();
ln.zDDEInit()``
See Also
--------
createLink()
"""
PyZDDE.__chNum += 1 # increment channel count
self._appName = _getAppName(PyZDDE.__appNameDict) or '' # wicked :-)
self._appNum = PyZDDE.__chNum # unique & immutable identity of each instance
self._connection = False # 1/0 depending on successful connection or not
self._macroPath = None # variable to store macro path
self._filesCreated = set() # .cfg & other files to be cleaned at session end
self._apr = apr
def __repr__(self):
return ("PyZDDE(appName=%r, appNum=%r, connection=%r, macroPath=%r)" %
(self._appName, self._appNum, self._connection, self._macroPath))
def __hash__(self):
# for storing in internal dictionary
return hash(self._appNum)
def __eq__(self, other):
return (self._appNum == other._appNum)
@property
def apr(self):
return self._apr
@apr.setter
def apr(self, val):
self._apr = val
# ZEMAX <--> PyZDDE client connection methods
#--------------------------------------------
def zDDEInit(self):
"""Initiates DDE link with Zemax server.
Usage: ``ln.zDDEInit()``
Parameters
----------
None
Returns
-------
status : integer (0 or -1)
0 = DDE Zemax link successful;
-1 = DDE link couldn't be established.
See Also
--------
createLink(), zDDEClose(), zDDEStart(), zSetTimeout()
"""
_debugPrint(1,"appName = " + self._appName)
_debugPrint(1,"liveCh = " + str(PyZDDE.__liveCh))
# do this only one time or when there is no channel
if PyZDDE.__liveCh==0:
try:
PyZDDE.__server = _dde.CreateServer()
PyZDDE.__server.Create("ZCLIENT") # Name of the client
_debugPrint(2, "PyZDDE.__server = " + str(PyZDDE.__server))
except Exception as err1:
_sys.stderr.write("{err}: Another application may be"
" using a DDE server!".format(err=str(err1)))
return -1
# Try to create individual conversations for each ZEMAX application.
self._conversation = _dde.CreateConversation(PyZDDE.__server)
_debugPrint(2, "PyZDDE.converstation = " + str(self._conversation))
try:
self._conversation.ConnectTo(self._appName," ")
except Exception as err2:
_debugPrint(2, "Exception occured at attempt to call ConnecTo."
" Error = {err}".format(err=str(err2)))
if self.__liveCh >= _MAX_PARALLEL_CONV:
_sys.stderr.write("ERROR: {err}. \nMore than {liveConv} "
"simultaneous conversations not allowed!\n"
.format(err=str(err2), liveConv =_MAX_PARALLEL_CONV))
else:
_sys.stderr.write("ERROR: {err}.\nZEMAX may not be running!\n"
.format(err=str(err2)))
# should close the DDE server if it exist
self.zDDEClose()
_debugPrint(2,"PyZDDE server: " + str(PyZDDE.__server))
return -1
else:
_debugPrint(1,"Zemax instance successfully connected")
PyZDDE.__liveCh += 1 # increment the number of live channels
self._connection = True
return 0
def close(self):
"""Helper function to close current communication link
Usage: ``ln.close()``
Parameters
----------
None
Returns
-------
None
Notes
-----
This bounded method provides a quick alternative way to close link
rather than calling the module function ``pyz.closeLink()``.
See Also
--------
zDDEClose() :
PyZDDE instance method to close a link.
Use this method (as ``ln.zDDEClose()``) if the link was
created as ``ln = pyz.PyZDDE(); ln.zDDEInit()``
closeLink() :
A moudle level function to close a link.
Use this method (as ``pyz.closeLink(ln)``) or ``ln.close()``
if the link was created as ``ln = pyz.createLink()``
"""
return closeLink(self)
def zDDEClose(self):
"""Close the DDE link with Zemax server.
Usage: ``ln.zDDEClose()``
Parameters
----------
None
Returns
-------
status : integer
0 on success.
Notes
-----
Use this bounded method to close link if the link was created using
the idiom ``ln = pyz.PyZDDE(); ln.zDDEInit()``. If however, the
link was created using ``ln = pyz.createLink()``, use either
``pyz.closeLink()`` or ``ln.close()``.
"""
if PyZDDE.__server and not PyZDDE.__liveCh:
PyZDDE.__server.Shutdown(self._conversation)
PyZDDE.__server = 0
_debugPrint(2,"server shutdown as ZEMAX is not running!")
elif PyZDDE.__server and self._connection and PyZDDE.__liveCh == 1:
PyZDDE.__server.Shutdown(self._conversation)
self._connection = False
PyZDDE.__appNameDict[self._appName] = False # make the name available
_deleteFilesCreatedDuringSession(self)
self._appName = ''
PyZDDE.__liveCh -= 1 # This will become zero now. (reset)
PyZDDE.__server = 0 # previous server obj should be garbage collected
_debugPrint(2,"server shutdown")
elif self._connection: # if additional channels were successfully created.
PyZDDE.__server.Shutdown(self._conversation)
self._connection = False
PyZDDE.__appNameDict[self._appName] = False # make the name available
_deleteFilesCreatedDuringSession(self)
self._appName = ''
PyZDDE.__liveCh -= 1
_debugPrint(2,"liveCh decremented without shutting down DDE channel")
else: # if zDDEClose is called by an object which didn't have a channel
_debugPrint(2, "Nothing to do")
return 0
def zSetTimeout(self, time):
"""Set global timeout value, in seconds, for all Zemax DDE calls.
Parameters
----------
time: integer
timeout value in seconds (if float is given, it is rounded to
integer)
Returns
-------
timeout : integer
the set timeout value in seconds
Notes
-----
This is a global timeout value. Some methods provide means to set
individual timeout values.
See Also
--------
zDDEInit()
"""
self._conversation.SetDDETimeout(round(time))
return self._conversation.GetDDETimeout()
def zGetTimeout(self):
"""Returns the current value of the global timeout in seconds
Parameters
----------
None
Returns
-------
timeout : integer
globally set timeout value in seconds
"""
return self._conversation.GetDDETimeout()
@autopushandrefresh
def _sendDDEcommand(self, cmd, timeout=None):
"""Method to send command to DDE client
"""
global _global_pyver3
reply = self._conversation.Request(cmd, timeout)
if _global_pyver3:
reply = reply.decode('ascii').rstrip()
return reply
def __del__(self):
"""Destructor"""
_debugPrint(2,"Destructor called")
self.zDDEClose()
# ****************************************************************
# ZEMAX DATA ITEM BASED METHODS
# ****************************************************************
def zCloseUDOData(self, bufferCode):
"""Close the User Defined Operand buffer allowing optimizer to
proceed
Parameters
----------
bufferCode : integer
buffercode is an integer value provided by Zemax to the client
that uniquely identifies the correct lens.
Returns
-------
retVal : ?
See Also
--------
zGetUDOSystem(), zSetUDOItem()
"""
return int(self._sendDDEcommand("CloseUDOData,{:d}".format(bufferCode)))
def zDeleteConfig(self, number):
"""Deletes an existing configuration (column) in the multi-
configuration editor
Parameters
----------
number : integer
configuration number to delete
Returns
-------
deleted_config_num : integer
configuration number deleted
Notes
-----
After deleting the configuration, all succeeding configurations
are re-numbered.
See Also
--------
zInsertConfig()
zDeleteMCO() :
(TIP) use zDeleteMCO to delete a row/operand
"""
return int(self._sendDDEcommand("DeleteConfig,{:d}".format(number)))
def zDeleteMCO(self, operNum):
"""Deletes an existing operand (row) in the multi-configuration
editor
Parameters
----------
operNum : integer
operand number (row in the MCE) to delete
Returns
-------
newNumberOfOperands : integer
new number of operands
Notes
-----
After deleting the row, all succeeding rows (operands) are
re-numbered.
See Also
--------
zInsertMCO()
zDeleteConfig() :
(TIP) Use zDeleteConfig() to delete a column/configuration.
"""
return int(self._sendDDEcommand("DeleteMCO,"+str(operNum)))
def zDeleteMFO(self, operand):
"""Deletes an optimization operand (row) in the merit function
editor
Parameters
----------
operand : integer
Operand (row) number (- 1 <= operand <= number_of_operands)
Returns
-------
newNumOfOperands : integer
the new number of operands
See Also
--------
zInsertMFO()
"""
return int(self._sendDDEcommand("DeleteMFO,{:d}".format(operand)))
def zDeleteObject(self, surfNum, objNum):
"""Deletes the NSC object identified by the ``objNum`` and
the surface identified by ``surfNum``
Parameters
----------
surfNum : integer
surface number of Non-Sequential Component surface
objNum : integer
object number in the NSC editor
Returns
-------
status : integer (0 or -1)
0 if successful, -1 if it failed
Notes
-----
1. The ``surfNum`` is 1 if the lens is purely NSC mode.
2. If no more objects are present it simply returns 0.
See Also
--------
zInsertObject()
"""
cmd = "DeleteObject,{:d},{:d}".format(surfNum,objNum)
reply = self._sendDDEcommand(cmd)
rs = reply.rstrip()
if rs == 'BAD COMMAND':
return -1
else:
return int(float(rs))
def zDeleteSurface(self, surfNum):
"""Deletes an existing surface identified by ``surfNum``
Parameters
----------
surfNum : integer
the surface number of the surface to be deleted
Returns
-------
status : integer
0 if successful
.. warning:: Although you cannot delete an object the function \
doesn't return an error (returns 0 instead).
See Also
--------
zInsertSurface()
"""
cmd = "DeleteSurface,{:d}".format(surfNum)
reply = self._sendDDEcommand(cmd)
return int(float(reply))
def zExportCAD(self, fileName, fileType=1, numSpline=32, firstSurf=1,
lastSurf=-1, raysLayer=1, lensLayer=0, exportDummy=0,
useSolids=1, rayPattern=0, numRays=0, wave=0, field=0,
delVignett=1, dummyThick=1.00, split=0, scatter=0,
usePol=0, config=0):
"""Export lens data in IGES/STEP/SAT format for import into CAD
programs
Parameters
----------
fileName : string
filename including extension (including full path is
recommended)
fileType : integer (0, 1, 2 or 3)
0 = IGES; 1 = STEP (default); 2 = SAT; 3 = STL
numSpline : integer
number of spline segments to use (default = 32)
firstSurf : integer
the first surface to export; the first object to export
(in NSC mode)
lastSurf : integer
the last surface to export; the last object to export
(in NSC mode)
(default = -1, i.e. image surface)
raysLayer : integer
layer to place ray data on (default = 1)
lensLayer : integer
layer to place lens data on (default = 0)
exportDummy : integer (0 or 1)
export dummy surface? 1 = export; 0 (default) = not export
useSolids : integer (0 or 1)
export surfaces as solids? 1 (default) = surfaces as solids;
rayPattern : integer (0 <= rayPattern <= 7)
0 (default) = XY fan; 1 = X fan; 2 = Y fan; 3 = ring; 4 = list;
5 = none; 6 = grid; 7 = solid beams.