Skip to main content

Simple optical ray tracing library to validate the design of an optical system (lenses positions and sizes, focal lengths, aperture and field stops). Support for Monte Carlo raytracing to estimate transmission efficiency and powers, limited but functional Zemax file loader for lenses, several material dispersion curves included for chromatic aberrations all coming from

Project description


by Prof. Daniel Côté and his group

This code aims to provide a simple ray tracing module for calculating various properties of optical paths (object, image, aperture stops, field stops). It makes use of ABCD matrices and does not consider spherical aberrations but can compute chromatic aberrations for simple cases when the materials are known. Since it uses the ABCD formalism (or Ray matrices, or Gauss matrices) it can perform tracing of rays and gaussian laser beams.

It is not a package to do "Rendering in 3D with raytracing".

The code has been developed first for teaching purposes and is used in my "Optique" Study Notes (french only), but also for actual use in my research. As of January 21st, 2021, there is an extensive, freely accessible tutorial in Journal of Neurophotonics:

"Tools and tutorial on practical ray tracing for microscopy"

by V. Pineau Noël*, S. Masoumi*, E. Parham*, G. Genest, L. Bégin, M.-A. Vigneault, D. C. Côté, Neurophotonics, 8(1), 010801 (2021). *Equal contributions. Permalink:

The published tutorial assumes version 1.3.x. There are video tutorials (in french, with english subtitles) on YouTube. We have made no attempts at making high performance code. Readability and simplicity of usage are the key here. It is a module with a few files, and only matplotlib and numpy as dependent modules.

The module defines Ray , Matrix, MatrixGroup and ImagingPath as the main elements for tracing rays. Matrix and MatrixGroup are either one or a sequence of many matrices into which Ray will propagate. ImagingPath is also a sequence of elements, with an object at the front edge. Specific subclasses of Matrix exists: Space, Lens, ThicklLens, and Aperture. Finally, a ray fan is a collection of rays, originating from a given point with a range of angles.

We have tried to separate the calculation code (i.e. the matrices and subclasses) from the drawing code (figures and graphics). One can use the calculation code without any graphics calls.

If you want to perform calculations with coherent laser beams, then you use GaussianBeam and LaserPath. Everything is essentially the same, except that the formalism does not allow for the gaussian beam to be "blocked", hence any calculation of stops with aperture are not available in LaserPath. That part of the code is less developed, but it is nevertheless available.

What's new?

To get information about what is new, currently the best place is the release page on GitHub.

The article above is fully compatible with all 1.3.x versions. As long as the API does not change, versions will be 1.3.x.

Installing and upgrading

You need matplotlib, which is a fairly standard Python module. If you do not have it, installing Anaconda is your best option. Python 3.6 or later is required. There are several ways to install the module:

  1. Simplest: pip install raytracing or pip install --upgrade raytracing
    1. If you need to install pip, download and run it with python
  2. If you download the source of the module, then you can type: python install
  3. From GitHub, you can get the latest version (including bugs, which are 153% free!) and then type python install
  4. If you are completely lost, copying the folder raytracing (the one that includes from the source file into the same directory as your own script will work.
  5. Watch the tutorial with subtitles here.

Getting started

The simplest way to import the package in your own scripts after installing it:

from raytracing import *

This will import Ray , GaussianBeam, and several Matrix elements such as Space, Lens, ThickLens, Aperture, DielectricInterface, but also MatrixGroup (to group elements together), ImagingPath (to ray trace with an object at the front edge), LaserPath (to trace a gaussian laser beam from the front edge) and a few predefined other such as Objective (to create a very thick lens that mimicks an objective).

You create an ImagingPath or a LaserPath, which you then populate with optical elements such as Space, Lens or Aperture or vendor lenses. You can then adjust the path properties (object height in ImagingPath for instance or inputBeam for LaserPath) and display in matplotlib. You can create a group of elements with MatrixGroup for instance a telescope, a retrofocus or any group of optical elements you would like to treat as a "group". The Thorlabs and Edmund optics lenses, for instance, are defined as MatrixGroups.

This will show you a list of examples of things you can do (more on that in the Examples section):

python -m raytracing -l           # List examples
python -m raytracing -e all       # Run all of them
python -m raytracing -e 1,2,4,6   # Only run 1,2,4 and 6

or request help with:

python -m raytracing -h

In your code, you would do this:

from raytracing import *

path = ImagingPath()
path.append(Lens(f=50, diameter=25))

You can also call display() on an element to see the cardinal points, principal planes, BFL and FFL. You can do it with any single Matrix element but also with MatrixGroup.

from raytracing import *




Finally, an addition as of 1.2.0 is the ability to obtain the intensity profile of a given source from the object plane at the exit plane of an OpticalPath. This is in fact really simple: by tracing a large number of rays, with the number of rays at y and θ being proportionnal to the intensity, one can obtain the intensity profile by plotting the histogram of rays reaching a given height at the image plane. Rays are small classes that return a Ray that satisfies the condition of the class. Currently, there is UniformRays,RandomUniformRays LambertianRays and RandomLambertianRays (a Lambertian distribution follows a cosθ distribution, it is a common diffuse surface source). They appear like iterators and can easily be used like this example script:

from raytracing import *
from numpy import *
import matplotlib.pyplot as plt

# Kohler illumination with these variables
fobj = 5
dObj = 5
f2 = 200
d2 = 50
f3 = 100
d3 = 50

# We build the path (i.e. not an Imaging path)
path = OpticalPath()
path.append(Lens(f=f3, diameter=d3))
path.append(Lens(f=f2, diameter=d2))
path.append(Lens(f=fobj, diameter=dObj))

# Obtaining the intensity profile
nRays = 1000000 # Increase for better resolution 
inputRays = RandomLambertianRays(yMax=2.5, maxCount=nRays)
inputRays.display("Input profile")
outputRays = path.traceManyThrough(inputRays, progress=True)
# On macOS and Linux, you can do parallel computations
# outputRays = path.traceManyThroughInParallel(inputRays, progress=True, processes=8) 
outputRays.display("Output profile")

and you will get the following ray histograms:

inputProfile outputProfile

Finally, it is possible to obtain the chromatic aberrations for compound lenses (achromatic doublets from Thorlabs and Edmund optics, and singlet lens because the materials are known). The following command will give you the focal shift as a function of wavelength (as a graph or values):

from raytracing import *

wavelengths, shifts = thorlabs.AC254_100_A().focalShifts()


All the documentation is available online.

The class hierarchy for optical elements (with parameters and defaults) is:


You may obtain help by:

  1. Reading the documentation for the code (API reference).
    1. Core:
      1. Ray: a ray for geometrical optics with a height and angle $y$ and $\theta$.
      2. Rays: ray distributions to ray trace an object through the optical system.
        1. UniformRays, RandomUniformRays, LambertianRays and RandomLambertianRays are currently available. See example above.
      3. GaussianBeam: a gaussian laser beam with complex radius of curvature $q$.
      4. Matrix: any 2x2 matrix.
      5. MatrixGroup: treats a group of matrix as a unit (draws it as a unit too)
      6. ImagingPath: A MatrixGroup with an object at the front for geometrical optics
      7. LaserPath: A MatrixGroup with a laser beam input at the front or a Resonator.
    2. Optical elements: Aperture, Space, Lens, DielectricInterface, DielectricSlab, ThickLens
    3. Specialty lenses: Defines a general achromat and objective lens
    4. Thorlabs lenses: Achromat doublet lenses from Thorlabs.
    5. Edmund Optics lenses: Achromat doublet lenses from Edmund Optics
    6. Olympus objectives: A few objectives from Olympus.
    7. Glasses: A few glasses used by Thorlabs to make achromatic doublets. They all have a single function n(wavelength) that returns the index at that wavelength. All data obtained from
    8. Zemax ZMX file reader: to read text-based Zemax files of lenses.
  2. typing (interactively): help(Matrix),help(MatrixGroup) help(Ray),help(ImagingPath) to get the API,
  3. look at the examples with python -m raytracing
  4. simply look at the code.
>>> help(Matrix)
Help on class Matrix in module raytracing.abcd:

class Matrix(builtins.object)
 |  Matrix(A, B, C, D, physicalLength=0, apertureDiameter=inf, label='')
 |  A matrix and an optical element that can transform a ray or another
 |  matrix.
 |  The general properties (A,B,C,D) are defined here. The operator "*" is
 |  overloaded to allow simple statements such as:
 |  ray2 = M1 * ray
 |  or
 |  M3 = M2 * M1
 |  The physical length is included in the matrix to allow simple management of
 |  the ray tracing. IF two matrices are multiplied, the resulting matrice
 |  will have a physical length that is the sum of both matrices.
 |  In addition finite apertures are considered: if the apertureDiameter
 |  is not infinite (default), then the object is assumed to limit the
 |  ray height to plus or minus apertureDiameter/2 from the front edge to the back
 |  edge of the element.
 |  Methods defined here:
 |  __init__(self, A, B, C, D, physicalLength=0, apertureDiameter=inf, label='')
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  __mul__(self, rightSide)
 |      Operator overloading allowing easy to read matrix multiplication
 |      For instance, with M1 = Matrix() and M2 = Matrix(), one can write
 |      M3 = M1*M2. With r = Ray(), one can apply the M1 transform to a ray
 |      with r = M1*r
 |  __str__(self)
 |      String description that allows the use of print(Matrix())
 |  backwardConjugate(self)
 |      With an image at the back edge of the element,
 |      where is the object ? Distance before the element by
 |      which a ray must travel to reach the conjugate plane at
 |      the back of the element. A positive distance means the
 |      object is "distance" in front of the element (or to the
 |      left, or before).
 |      M2 = M1*Space(distance)
 |      # M2.isImaging == True


You can list several examples python -m raytracing -l:

All example code on your machine is found at: /somedirectory/on/your/machine
 1. A single lens f = 50 mm, infinite diameter
 2. Two lenses, infinite diameters
 3. Finite-diameter lens
 4. Aperture behind lens acting as Field Stop
 5. Simple microscope system
 6. Kohler illumination
 7. Focussing through a dielectric slab
 8. Virtual image at -f with object at f/2
 9. Infinite telecentric 4f telescope
10. Retrofocus $f_e$={0:.1f} cm, and BFL={1:.1f}
11. Thick diverging lens computed from the Lensmaker equation
12. Thick diverging lens built from individual elements
13. Obtain the forward and backward conjugates
14. Generic objectives
15. Model Olympus objective LUMPlanFL40X
16. Commercial doublets from Thorlabs and Edmund
17. An optical system with vendor lenses
18. Laser beam and vendor lenses
19. Cavity round trip and calculated laser modes
.... and more complete examples at /somedirectory/on/your/machine

You can run them all with python -m raytracing -e all (see them all below) to get a flavour of what is possible (note: in the US, it will give you a flavor of what is possible instead). Notice the command will tell you where the directory with all the tests is on your machine. You will find more complete examples in that examples directory, distributed with the module. For instance, to see a Kohler illuminator, and to see an example of the role of lens diameters to determine the field of view.




















Known limitations

There are no known bugs in the actual calculations, but there are bugs or limitations in the display:

  1. It is not easy to put several labels on a graph without any overlap. We are still working on it.
  2. It is also not easy to figure out what "the right size" should be for an arrow head, the font, the position of a label, the size of the "ticks" on the aperture.
  3. Labelling focal points with appropriate secondary labels should be possible, maybe a superscript?
  4. The y-scale is not always set appropriately when the elements have infinite diameters: the rays will go beyond the element drawn on the figure.


This code is provided under the MIT License.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for raytracing, version 1.3.7
Filename, size File type Python version Upload date Hashes
Filename, size raytracing-1.3.7.tar.gz (1.6 MB) File type Source Python version None Upload date Hashes View
Filename, size raytracing-1.3.7-py3-none-any.whl (1.6 MB) File type Wheel Python version py3 Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page