Using PyZDDE with IPython webnotebook

NOTE: This notebook was opened using the following command from the shell "ipython notebook --pylab inline"

Using the IPython webnotebook with Zemax via the PyZDDE toolbox is an attractive application as:

  • It can provide a way for quick documentation of a lens design process as one progress through the design, including embedding intermittent figures, prescription files, thought process, etc.
  • It can also be used in an educational setting, such as to create and distribute lectures.

Embedding Graphic

Ways of embedding Zemax graphic into the IPython webnotebook:

There are mainly 2 ways of embedding the graphic windows from within Zemax into the Webnotebook (or IPython QtConsole) --

  1. Using the commands ipzCaptureWindow and ipzCaptureWindow2. ipzCaptureWindow basically exports JPG images from Zemax and embeds them into the IPython QtConsole or notebook cell. The quality of the embedded JPG image is limited by the JPG export quality from Zemax. If better quality graphics is desired, then use ipzCaptureWindow2.
  2. ipzCaptureWindow2 requests Zemax to export the grahics as Metafile (WMF/EMF), resizes, converts to PNG, and then embeds them into the IPython shell.

Using `ipzCaptureWindow`:

The function ipzCaptureWindow is useful for quickly capturing a graphic window, and embedding into an IPython Webnotebook or QtConsole.

In order to use this function, please copy the ZPL macros from PyZDDE\ZPLMacros to the macro directory where Zemax is expecting the ZPL macros to be (i.e. the folder set in Zemax->Preference->Folders->ZPL).

1. First, confirm that Zemax is running

2. import pyzdde and create a PyZDDE object

In [1]:
import pyzdde.zdde as pyz
l = pyz.PyZDDE()

3. Initialize pyzdde

In [2]:
l.zDDEInit()
Out[2]:
0

4. It is important to set the path to the Zemax Macro now (if the macro path is not the default macro path)

In [3]:
l.zSetMacroPath(r"C:\PROGRAMSANDEXPERIMENTS\ZEMAX\Macros")
Out[3]:
0

5. Before exiting, please use `zDDEClose()` to close the DDE communication

Example 1

Load a lens into the Zemax DDE server

In [4]:
l.zLoadFile(r'C:\Users\Indranil\Documents\ZEMAX\Samples\Sequential\Objectives\Cooke 40 degree field.zmx')
Out[4]:
0

Get lens information:

In [5]:
l.zGetFile()
Out[5]:
'C:\\Users\\Indranil\\Documents\\ZEMAX\\Samples\\Sequential\\Objectives\\Cooke 40 degree field.zmx'

Plot (using Matplotlib) a spot diagram using `spiralSpot()` function

In [6]:
x,y,_,_ = l.zSpiralSpot(0.0,0.4,1,10,1000)
In [7]:
figsize(8,5) # Set figure size of IPython figure # required to have opened the notebook with --pylab inline
sp = scatter(x, y, s=5, c='red', linewidth=0.35)
grid()
ax = gca()
ax.set_aspect('equal')
In [8]:
# Note that the kernel is going to be busy for a little time
hx = 0.0
hy = 0.4
spirals = 100
rays = 6000
xb,yb,_,_ = l.zSpiralSpot(hx,hy,1,spirals,rays)
xg,yg,_,_ = l.zSpiralSpot(hx,hy,2,spirals,rays)
xr,yr,_,_ = l.zSpiralSpot(hx,hy,3,spirals,rays)
In [9]:
figsize(10,6)
ax = plt.gca()
fig = plt.gcf()
ax.set_aspect('equal')
ax.scatter(xr,yr,s=5,c='red',linewidth=0.35,zorder=20)
ax.scatter(xg,yg,s=5,c='lime',linewidth=0.35,zorder=21)
ax.scatter(xb,yb,s=5,c='blue',linewidth=0.35,zorder=22)
ax.set_xlabel('x');ax.set_ylabel('y')
fig.suptitle('Spiral Spot')
ax.grid(color='lightgray', linestyle='-', linewidth=1)
ax.ticklabel_format(scilimits=(-2,2))

Push lens from the DDE server to the LDE editor

In [10]:
if l.zPushLensPermission():
    l.zPushLens(updateFlag=1)

Now, maximize the Zemax main window, and open any of the analysis windows such as the 2D Layout plot, MTF, spot diagram, etc. We will embed the open windows here using the particular window number. Please note that the analysis window in Zemax needs to be open.

Embedding graphic windows from Zemax using **`ipzCaptureWindow()`**

Here is the docstring of the function ipzCaptureWindow()

In [13]:
print l.ipzCaptureWindow.__doc__
Capture graphic window from Zemax and display in IPython.

        ipzCaptureWindow(num [, *args, **kwargs])-> displayGraphic

        Parameters
        ----------
        num: The graphic window to capture is indicated by the window number `num`.

        This function is useful for quickly capturing a graphic window, and
        embedding into a IPython Webnotebook or QtConsole. The quality of JPG
        image is limited by the JPG export quality from Zemax.

        NOTE:
        ----
        In order to use this function, please copy the ZPL macros from
        PyZDDE\ZPLMacros to the macro directory where Zemax is expecting (i.e.
        as set in Zemax->Preference->Folders)
        

2D Layout plot

Note that the window numbers are not absolutely tied to any particular analysis type. The input parameter to ipzCaptureWindow is the window number as shown in Zemax.

In [12]:
l.ipzCaptureWindow(1)

Ray Fan

In [17]:
l.ipzCaptureWindow(2)

MTF

In [19]:
l.ipzCaptureWindow(3)

Spot Diagram

In [21]:
l.ipzCaptureWindow(4)

Using `ipzCaptureWindow2`:

Docstring of ipzCaptureWindow2()

In [22]:
print l.ipzCaptureWindow2.__doc__
Capture any analysis window from Zemax main window, using 3-letter analysis code.

        This is similar to ipzCaptureWindow, but more capable, and generally produces
        better graphic output. It uses the metafile exported by Zemax as its
        source image, converts the metafile into PNG using ImageMagic's convert
        program and displays/embeds the PNG image on the IPython Webnotebook or
        QtConsole.

        ipzCaptureWindow2(analysisType [,percent=12,MFFtNum=0,blur=1, gamma=0.35,
                         settingsFileName=None, flag=0]) -> displayGraphic

        Parameters
        ----------
        analysisType  : 3-letter button code for the type of analysis
        percent       : (float) percentage of the metafile to display (default=12)
        MFFtNum       : (integer) 0 = Enhanced Metafile, 1 = Standard Metafile
        blur          : (float) Amount of blurring to use for antialiasing during
                         resizing of metafile (default=1)
        gamma         : (float) gamma for the PNG image (default = 0.35). Use
                        a gamma value of around 0.9 for color surface plots.
        settingsFileName : If a valid file name is used for the "settingsFileName",
                           ZEMAX will use or save the settings used to compute the
                           metafile, depending upon the value of the flag parameter.
        flag        :  0 = default settings used for the metafile graphic
                       1 = settings provided in the settings file, if valid,
                           else default settings used
                       2 = settings provided in the settings file, if valid,
                           will be used and the settings box for the requested
                           feature will be displayed. After the user makes any
                           changes to the settings the graphic will then be
                           generated using the new settings.
        

2D Layout plot

In [13]:
l.ipzCaptureWindow2('Lay')

Ray Fan plot

In [25]:
# Ray fan plot (for field 3)
l.ipzCaptureWindow2('Ray',gamma=0.4)
In [30]:
# FFT PSF (for field 3)
l.ipzCaptureWindow2('Fps', gamma=0.85)

Insert Lens Prescription file here

In [31]:
l.ipzGetTextWindow('Pre')
C:\Users\Indranil\Documents\ZEMAX\SAMPLES\TEMPTXT.txt
System/Prescription Data

File : C:\Users\Indranil\Documents\ZEMAX\Samples\Sequential\Objectives\Cooke 40 degree field.zmx
Title: A SIMPLE COOKE TRIPLET.
Date : 6/22/2013


LENS NOTES:

Notes...
 
 
GENERAL LENS DATA:

Surfaces                :                7
Stop                    :                4
System Aperture         : Entrance Pupil Diameter = 10
Glass Catalogs          : SCHOTT
Ray Aiming              : Off
Apodization             : Uniform, factor =   0.00000E+000
Temperature (C)         :    2.00000E+001
Pressure (ATM)          :    1.00000E+000
Adjust Index Data To Environment  : Off
Effective Focal Length  :              50 (in air at system temperature and pressure)
Effective Focal Length  :              50 (in image space)
Back Focal Length       :        42.41508
Total Track             :        60.17675
Image Space F/#         :               5
Paraxial Working F/#    :               5
Working F/#             :         4.97822
Image Space NA          :      0.09950372
Object Space NA         :          5e-010
Stop Radius             :        3.800852
Paraxial Image Height   :        18.19851
Paraxial Magnification  :               0
Entrance Pupil Diameter :              10
Entrance Pupil Position :        11.51216
Exit Pupil Diameter     :        10.23373
Exit Pupil Position     :       -50.96134
Field Type              : Angle in degrees
Maximum Radial Field    :              20
Primary Wavelength      :            0.55 µm
Lens Units              :   Millimeters
Angular Magnification   :        0.977161

Fields          : 3
Field Type              : Angle in degrees
 #        X-Value        Y-Value         Weight
 1       0.000000       0.000000       1.000000
 2       0.000000      14.000000       1.000000
 3       0.000000      20.000000       1.000000

Vignetting Factors
 #       VDX       VDY       VCX       VCY       VAN
 1  0.000000  0.000000  0.000000  0.000000  0.000000
 2  0.000000  0.000000  0.000000  0.000000  0.000000
 3  0.000000  0.000000  0.000000  0.000000  0.000000

Wavelengths     : 3
Units: µm
 #          Value         Weight
 1       0.480000       0.800000
 2       0.550000       1.000000
 3       0.650000       0.800000

SURFACE DATA SUMMARY:

Surf     Type         Radius      Thickness                Glass      Diameter          Conic   Comment
 OBJ STANDARD       Infinity       Infinity                                  0              0 
   1 STANDARD       22.01359       3.258956                 SK16            19              0 
   2 STANDARD      -435.7604       6.007551                                 19              0 
   3 STANDARD      -22.21328      0.9999746                   F2            10              0 
 STO STANDARD       20.29192       4.750409                                 10              0 
   5 STANDARD        79.6836       2.952076                 SK16            15              0 
   6 STANDARD      -18.39533       42.20778                                 15              0 
 IMA STANDARD       Infinity                                          36.34532              0 

SURFACE DATA DETAIL:

Surface OBJ STANDARD 

Surface   1 STANDARD 
Coating                  : AR
Aperture                 : Floating Aperture
Maximum Radius           :              9.5

Surface   2 STANDARD 
Coating                  : AR
Aperture                 : Floating Aperture
Maximum Radius           :              9.5

Surface   3 STANDARD 
Coating                  : AR
Aperture                 : Floating Aperture
Maximum Radius           :                5

Surface STO STANDARD 
Coating                  : AR
Aperture                 : Floating Aperture
Maximum Radius           :                5

Surface   5 STANDARD 
Coating                  : AR
Aperture                 : Floating Aperture
Maximum Radius           :              7.5

Surface   6 STANDARD 
Coating                  : AR
Aperture                 : Floating Aperture
Maximum Radius           :              7.5

Surface IMA STANDARD 

COATING DEFINITIONS:


EDGE THICKNESS DATA:

Surf           Edge
   1       1.000000
   2       5.541077
   3       2.195669
 STO       4.478499
   5       0.999971
   6      43.806141
 IMA       0.000000

SOLVE AND VARIABLE DATA:

 Curvature of   1       : Variable
 Thickness of   1       : Variable
 Semi Diameter   1      : Fixed
 Curvature of   2       : Variable
 Thickness of   2       : Variable
 Semi Diameter   2      : Fixed
 Curvature of   3       : Variable
 Thickness of   3       : Variable
 Semi Diameter   3      : Fixed
 Curvature of   4       : Variable
 Thickness of   4       : Variable
 Semi Diameter   4      : Fixed
 Curvature of   5       : Variable
 Thickness of   5       : Variable
 Semi Diameter   5      : Fixed
 Curvature of   6       : Solve, Marginal ray exit angle = -0.1
 Thickness of   6       : Variable
 Semi Diameter   6      : Fixed

INDEX OF REFRACTION DATA:

System Temperature:   20.0000 Celsius
System Pressure   :    1.0000 Atmospheres
Absolute air index:    1.000273 at wavelength 0.550000 µm
Index data is relative to air at the system temperature and pressure.
Wavelengths are measured in air at the system temperature and pressure.

Surf                  Glass    Temp    Pres     0.480000   0.550000   0.650000
   0                          20.00    1.00   1.00000000 1.00000000 1.00000000
   1                   SK16   20.00    1.00   1.62813927 1.62260769 1.61752112 
   2                          20.00    1.00   1.00000000 1.00000000 1.00000000
   3                     F2   20.00    1.00   1.63309920 1.62365512 1.61542246 lead containing glass type        
   4                          20.00    1.00   1.00000000 1.00000000 1.00000000
   5                   SK16   20.00    1.00   1.62813927 1.62260769 1.61752112 
   6                          20.00    1.00   1.00000000 1.00000000 1.00000000
   7                          20.00    1.00   1.00000000 1.00000000 1.00000000

THERMAL COEFFICIENT OF EXPANSION DATA:

Surf                  Glass     TCE *10E-6
  0                             0.00000000
  1                    SK16     6.30000000 
  2                             0.00000000
  3                      F2     8.20000000 lead containing glass type        
  4                             0.00000000
  5                    SK16     6.30000000 
  6                             0.00000000
  7                             0.00000000

GLOBAL VERTEX COORDINATES, ORIENTATIONS, AND ROTATION/OFFSET MATRICES:

Reference Surface: 1

Surf           R11            R12            R13                 X
               R21            R22            R23                 Y
               R31            R32            R33                 Z

  1   1.0000000000   0.0000000000   0.0000000000  0.000000000E+000 
      0.0000000000   1.0000000000   0.0000000000  0.000000000E+000
      0.0000000000   0.0000000000   1.0000000000  0.000000000E+000

  2   1.0000000000   0.0000000000   0.0000000000  0.000000000E+000 
      0.0000000000   1.0000000000   0.0000000000  0.000000000E+000
      0.0000000000   0.0000000000   1.0000000000  3.258955830E+000

  3   1.0000000000   0.0000000000   0.0000000000  0.000000000E+000 
      0.0000000000   1.0000000000   0.0000000000  0.000000000E+000
      0.0000000000   0.0000000000   1.0000000000  9.266506930E+000

  4   1.0000000000   0.0000000000   0.0000000000  0.000000000E+000 
      0.0000000000   1.0000000000   0.0000000000  0.000000000E+000
      0.0000000000   0.0000000000   1.0000000000  1.026648150E+001

  5   1.0000000000   0.0000000000   0.0000000000  0.000000000E+000 
      0.0000000000   1.0000000000   0.0000000000  0.000000000E+000
      0.0000000000   0.0000000000   1.0000000000  1.501689043E+001

  6   1.0000000000   0.0000000000   0.0000000000  0.000000000E+000 
      0.0000000000   1.0000000000   0.0000000000  0.000000000E+000
      0.0000000000   0.0000000000   1.0000000000  1.796896607E+001

  7   1.0000000000   0.0000000000   0.0000000000  0.000000000E+000 
      0.0000000000   1.0000000000   0.0000000000  0.000000000E+000
      0.0000000000   0.0000000000   1.0000000000  6.017674617E+001


GLOBAL Surface CENTER OF CURVATURE POINTS:

Reference Surface: 1

Surf             X              Y              Z
  1   0.0000000000   0.0000000000  22.0135925084 
  2   0.0000000000   0.0000000000 -432.5014803383 
  3   0.0000000000   0.0000000000 -12.9467702523 
  4   0.0000000000   0.0000000000  30.5584056223 
  5   0.0000000000   0.0000000000  94.7004929775 
  6   0.0000000000   0.0000000000  -0.4263665360 
  7              -              -              - 

ELEMENT VOLUME DATA:

For centered elements with plane or spherical circular faces, exact
volumes are computed by assuming edges are squared up to the larger
of the front and back radial aperture.

For all other elements, approximate volumes are numerically integrated
to 0.1% accuracy. Zero volume means the volume cannot be accurately computed.

Single elements that are duplicated in the Lens Data Editor
for ray tracing purposes may be listed more than once yielding
incorrect total mass estimates.

                             Volume cc   Density g/cc         Mass g
Element surf   1 to   2       0.609012       3.580000       2.180262
Element surf   3 to   4       0.125267       3.599000       0.450837
Element surf   5 to   6       0.351353       3.580000       1.257845
Total Mass:                                                 3.888945

F/# DATA:

F/# calculations consider vignetting factors and ignore surface apertures.

             Wavelength:       0.480000           0.550000           0.650000    
#                Field       Tan       Sag      Tan       Sag      Tan       Sag
1           0.00 (deg):   4.9801    4.9801   4.9782    4.9782   4.9825    4.9825
2          14.00 (deg):   5.3344    5.1149   5.3350    5.1130   5.3419    5.1174
3          20.00 (deg):   5.6915    5.2853   5.7012    5.2837   5.7162    5.2885

CARDINAL POINTS:

Object space positions are measured with respect to surface 1.
Image space positions are measured with respect to the image surface.
The index in both the object space and image space is considered.

                               Object Space         Image Space
W = 0.480000
Focal Length          :          -49.988055           49.988055
Focal Planes          :          -37.301925            0.196773
Principal Planes      :           12.686131          -49.791282
Anti-Principal Planes :          -87.289980           50.184828
Nodal Planes          :           12.686131          -49.791282
Anti-Nodal Planes     :          -87.289980           50.184828

W = 0.550000(Primary)
Focal Length          :          -50.000000           50.000000
Focal Planes          :          -37.345894            0.207300
Principal Planes      :           12.654105          -49.792700
Anti-Principal Planes :          -87.345894           50.207299
Nodal Planes          :           12.654105          -49.792700
Anti-Nodal Planes     :          -87.345894           50.207299

W = 0.650000
Focal Length          :          -50.066098           50.066098
Focal Planes          :          -37.439691            0.273983
Principal Planes      :           12.626407          -49.792116
Anti-Principal Planes :          -87.505790           50.340081
Nodal Planes          :           12.626407          -49.792116
Anti-Nodal Planes     :          -87.505790           50.340081

PHYSICAL OPTICS PROPAGATION SETTINGS SUMMARY:

 OBJ STANDARD                    
Use Rays To Propagate To Next Surface  : Off
Recompute Pilot Beam                   : Off
Do Not Rescale Beam Size Using Ray Data: Off
Use Angular Spectrum Propagator        : Off
Output Pilot Radius                    : Best Fit
   1 STANDARD                    
Use Rays To Propagate To Next Surface  : Off
Recompute Pilot Beam                   : Off
Do Not Rescale Beam Size Using Ray Data: Off
Use Angular Spectrum Propagator        : Off
Output Pilot Radius                    : Best Fit
   2 STANDARD                    
Use Rays To Propagate To Next Surface  : Off
Recompute Pilot Beam                   : Off
Do Not Rescale Beam Size Using Ray Data: Off
Use Angular Spectrum Propagator        : Off
Output Pilot Radius                    : Best Fit
   3 STANDARD                    
Use Rays To Propagate To Next Surface  : Off
Recompute Pilot Beam                   : Off
Do Not Rescale Beam Size Using Ray Data: Off
Use Angular Spectrum Propagator        : Off
Output Pilot Radius                    : Best Fit
 STO STANDARD                    
Use Rays To Propagate To Next Surface  : Off
Recompute Pilot Beam                   : Off
Do Not Rescale Beam Size Using Ray Data: Off
Use Angular Spectrum Propagator        : Off
Output Pilot Radius                    : Best Fit
   5 STANDARD                    
Use Rays To Propagate To Next Surface  : Off
Recompute Pilot Beam                   : Off
Do Not Rescale Beam Size Using Ray Data: Off
Use Angular Spectrum Propagator        : Off
Output Pilot Radius                    : Best Fit
   6 STANDARD                    
Use Rays To Propagate To Next Surface  : Off
Recompute Pilot Beam                   : Off
Do Not Rescale Beam Size Using Ray Data: Off
Use Angular Spectrum Propagator        : Off
Output Pilot Radius                    : Best Fit
 IMA STANDARD                    
Use Rays To Propagate To Next Surface  : Off
Recompute Pilot Beam                   : Off
Do Not Rescale Beam Size Using Ray Data: Off
Use Angular Spectrum Propagator        : Off
Output Pilot Radius                    : Best Fit

FILES USED:

Zemax File
  C:\Users\Indranil\Documents\ZEMAX\Samples\Sequential\Objectives\Cooke 40 degree field.zmx
Session File
  C:\Users\Indranil\Documents\ZEMAX\Samples\Sequential\Objectives\Cooke 40 degree field.SES
Lens Configuration File
  C:\Users\Indranil\Documents\ZEMAX\Samples\Sequential\Objectives\Cooke 40 degree field.CFG
Glass Catalogs
  C:\Users\Indranil\Documents\ZEMAX\GLASSCAT\SCHOTT.AGF
Coating Data
  C:\Users\Indranil\Documents\ZEMAX\COATINGS\COATING.DAT
ABg Data
  C:\Users\Indranil\Documents\Zemax\ABG_DATA\ABG_DATA.DAT

Finally close the DDE communication

In [14]:
l.zDDEClose()
Out[14]:
0
In [ ]: