Python API
Designs can be scripted with one object, Bench: a row of lenses and apertures on an axis,
some fields of light and an image plane. Almost everything the window does can be scripted, apart from undo.
The API will change. RayCrafter is pre-alpha, and methods may be renamed without warning.
Contents: Start · Find lenses · Place and move lenses · Gaps and the source plane · Assemblies and user parts · Apertures and the stop · Fields · Finite objects · Focus and summary · Detector · Plots · Raw results · Across the field · Wavefront and colour · Collimation and glass · Image simulation · Named designs · Sweeps · Drive the window · Files and reports · Errors · Reference
Start
You need Python 3.12 or later. To install RayCrafter, with IPython, into a new environment:
pip install ipython raycrafter
ipython
Or, with uv and nothing to install: uvx --with raycrafter ipython.
All the examples below are one session, run top to bottom. A plot call returns a matplotlib Figure, shown
here under the command. In Jupyter, run %matplotlib inline first to see figures like this. In a terminal, save
them with .savefig("name.png").
Units and numbering
- Distances are in mm along the optical axis (z). Light travels towards larger z.
- Angles are in degrees, vergence in dioptres (positive converging), wavelengths in nm.
- Elements (lenses and apertures together) are numbered from 0 along the axis, fields from 0 in the order added. An element’s number changes if another is added in front of it or the two swap places.
Make a bench
Bench() starts like a new window, with one lens. Bench(empty=True) has none. Both are
headless: no window is involved.
In [1]: from raycrafter import Bench
In [2]: Bench()
Out[2]: <Bench (headless): 1 lens, 1 field, image at 310.0 mm>
In [3]: bench = Bench(empty=True)
In [4]: bench
Out[4]: <Bench (headless): 0 lenses, 1 field, image at 310.0 mm>
Find lenses
search_lenses filters the built-in catalogue. Results are sorted by absolute focal length.
In [5]: found = bench.search_lenses("AC254", min_focal_length_mm=49, max_focal_length_mm=101)
In [6]: for entry in found[:6]:
...: print(f"{entry.part_number:14} f = {entry.focal_length:6.1f} mm {entry.coating}")
AC254-050-C f = 50.0 mm C: 1050-1700 nm
AC254-050-AB f = 50.0 mm AB: 400-1100 nm
AC254-050-B f = 50.0 mm B: 650-1050 nm
AC254-050-A f = 50.2 mm A: 350-700 nm
AC254-060-C f = 60.0 mm C: 1050-1700 nm
AC254-060-B f = 60.1 mm B: 650-1050 nm
In [7]: negative = bench.search_lenses(max_focal_length_mm=-1, min_diameter_mm=24, category="Achromats")
In [8]: [entry.part_number for entry in negative[:5]]
Out[8]:
['ACN254-040-B',
'ACN254-040-A',
'ACN254-050-A',
'ACN254-050-B',
'ACN254-075-B']
In [9]: entry = bench.catalog["AC254-100-A"]
In [10]: entry.focal_length, entry.clear_diameter_mm, entry.category, entry.family
Out[10]: (100.1, 25.4, 'Achromats', 'Achromatic doublets')
Place and move lenses
Build a 2:1 beam reducer. Each call returns an ElementInfo snapshot.
In [11]: bench.add_lens("AC254-100-A")
Out[11]: ElementInfo(index=0, kind='lens', part_number='AC254-100-A', front_z_mm=100.0, back_z_mm=106.5, thickness_mm=6.5, clear_diameter_mm=25.4, focal_length_mm=100.1, flipped=False, assembly=None, assembly_name=None, is_paraxial=False, gap_after_mm=203.5, gap_after_locked=False, vendor='Thorlabs', mount_type=None, surface_range=(1, 3), is_stop=False, is_back_aperture=False)
In [12]: bench.add_lens("AC254-050-A", front_z_mm=250)
Out[12]: ElementInfo(index=1, kind='lens', part_number='AC254-050-A', front_z_mm=250.0, back_z_mm=261.5, thickness_mm=11.5, clear_diameter_mm=25.4, focal_length_mm=50.17, flipped=False, assembly=None, assembly_name=None, is_paraxial=False, gap_after_mm=48.5, gap_after_locked=False, vendor='Thorlabs', mount_type=None, surface_range=(4, 6), is_stop=False, is_back_aperture=False)
In [13]: bench.plot("ray_diagram")

move_element behaves like a drag: lenses stop at their neighbours, and swap places if pushed past them.
Snapshots do not update, so read
bench.elements again after an edit.
In [14]: bench.move_element(1, front_z_mm=245).front_z_mm
Out[14]: 245.0
In [15]: bench.move_element(1, front_z_mm=90).front_z_mm # push it past the other lens: they swap
Out[15]: 100.0
In [16]: [(e.index, e.part_number, e.front_z_mm) for e in bench.elements]
Out[16]: [(0, 'AC254-050-A', 100.0), (1, 'AC254-100-A', 250.0)]
Flip and delete work by index. An ideal (paraxial) lens takes any focal length.
In [17]: bench = Bench(empty=True)
In [18]: bench.add_lens("LA1509-A")
Out[18]: ElementInfo(index=0, kind='lens', part_number='LA1509-A', front_z_mm=100.0, back_z_mm=103.59, thickness_mm=3.59, clear_diameter_mm=25.4, focal_length_mm=100.0, flipped=False, assembly=None, assembly_name=None, is_paraxial=False, gap_after_mm=206.41, gap_after_locked=False, vendor='Thorlabs', mount_type=None, surface_range=(1, 2), is_stop=False, is_back_aperture=False)
In [19]: bench.flip_lens(0).flipped
Out[19]: True
In [20]: bench.add_paraxial_lens(150, front_z_mm=250).part_number
Out[20]: 'Paraxial f=+150 mm'
In [21]: bench.delete_element(1)
In [22]: len(bench.elements)
Out[22]: 1
A snapshot also describes the part and the air behind it:
In [23]: lens = Bench().elements[0]
In [24]: lens.part_number, lens.vendor, lens.focal_length_mm, lens.clear_diameter_mm
Out[24]: ('ACT508-200-A', 'Thorlabs', 200.0, 50.8)
In [25]: lens.surface_range, lens.gap_after_mm, lens.gap_after_locked
Out[25]: ((1, 3), 193.4, False)
Replace a lens
replace_lens swaps a lens for another, keeping its rear principal plane where it was. Give a part number or
a paraxial focal length.
In [26]: sketch = Bench(empty=True)
In [27]: sketch.add_paraxial_lens(200);
In [28]: sketch.autofocus()
Out[28]: 300.0
In [29]: real = sketch.replace_lens(0, "AC254-200-A")
In [30]: real.part_number, round(real.front_z_mm, 2)
Out[30]: ('AC254-200-A', 99.76)
In [31]: round(sketch.autofocus(), 2) # the focus has hardly moved
Out[31]: 300.2
Focal points and foci
key_planes lists the focal points of every lens and assembly, and the places where the selected field comes
to a focus. move_element_to puts an element exactly somewhere, or refuses.
In [32]: scope = Bench(empty=True)
In [33]: scope.add_paraxial_lens(10);
...: scope.add_paraxial_lens(200);
...: scope.set_image_z(600)
In [34]: scope.move_element_to(1, front_z_mm=330).front_z_mm
Out[34]: 330.0
In [35]: for plane in scope.key_planes():
...: print(f"{plane.z_mm:7.1f} {plane.label}")
90.0 F of Paraxial f=+10 mm
110.0 F′ of Paraxial f=+10 mm
110.0 focus of Field 0
130.0 F of Paraxial f=+200 mm
530.0 F′ of Paraxial f=+200 mm
In [36]: target = next(p for p in scope.key_planes() if p.label == "F of Paraxial f=+200 mm")
In [37]: # put the objective's rear focal plane (10 mm behind it) on the tube lens's front focal point
...: scope.move_element_to(0, front_z_mm=target.z_mm - 10).front_z_mm
Out[37]: 120.0
Gaps and the source plane
A gap is measured vertex to vertex: from the back of a lens to the front of the next one, or to the image plane
behind the last. set_gap types a gap, as in the window: all later lenses and the image plane shift
together, so no other gap changes.
In [38]: bench = Bench(empty=True)
In [39]: bench.add_lens("AC254-100-A");
...: bench.add_lens("AC254-050-A");
In [40]: bench.set_gap(0, 130).gap_after_mm
Out[40]: 130.0
In [41]: [e.front_z_mm for e in bench.elements]
Out[41]: [100.0, 236.5]
A locked gap keeps its length. Lenses joined by locked gaps move together.
In [42]: bench.lock_gap(0).gap_after_locked
Out[42]: True
In [43]: bench.move_element(0, front_z_mm=120);
In [44]: [e.front_z_mm for e in bench.elements]
Out[44]: [120.0, 256.5]
In [45]: bench.set_gap(0, 100) # raises
ValueError: This gap is locked: unlock it to change it
In [46]: bench.lock_gap(0, locked=False);
The source plane is where every field’s diameter, offset, angle and vergence are defined: a light source, a scan mirror or a stop. By default it is locked to the first lens, 0 mm in front of it. Unlock it to set the distance.
In [47]: bench.source_gap_mm, bench.source_gap_locked
Out[47]: (0.0, True)
In [48]: bench.lock_source_gap(False)
In [49]: bench.set_source_gap(50)
In [50]: bench.source_z_mm, bench.elements[0].front_z_mm
Out[50]: (120.0, 170.0)
set_source_z moves the source plane itself, leaving the lenses where they are.
Optimise a gap
optimise_gap finds, and by default sets, the gap behind an element that collimates the light
("collimate") or gives the smallest spot on the image plane ("focus"), using real rays of the
selected field. Element index −1 means the gap from the source plane.
In [51]: reducer = Bench(empty=True)
In [52]: reducer.add_lens("AC254-100-A");
...: reducer.add_lens("AC254-050-A");
In [53]: result = reducer.optimise_gap(0, "collimate", apply=False) # only look
In [54]: round(result.gap_after_mm, 3), round(result.merit_after, 1), result.merit_unit
Out[54]: (146.838, 78.5, 'µrad')
In [55]: # would turning a lens round do clearly better?
...: result.flip_element_index, round(result.flipped_gap_mm, 3), round(result.flipped_merit, 1)
Out[55]: (1, 140.49, 14.7)
In [56]: reducer.optimise_gap(0, "collimate", flip_if_better=True); # flip it, and set that gap
In [57]: round(reducer.elements[0].gap_after_mm, 3), reducer.elements[1].flipped
Out[57]: (140.49, True)
Assemblies and user parts
An assembly is a run of neighbouring lenses that moves and flips as one. The gaps inside it are locked. Save one as a user part and you can insert it into any design.
In [58]: relay = Bench(empty=True)
In [59]: relay.add_paraxial_lens(100);
...: relay.add_paraxial_lens(100);
...: relay.set_gap(0, 200);
In [60]: relay.make_assembly(0, 1, name="4f relay")
In [61]: [(e.assembly, e.assembly_name) for e in relay.elements]
Out[61]: [(1, '4f relay'), (1, '4f relay')]
In [62]: relay.save_user_part(0, "4f relay", overwrite=True)
Out[62]: PosixPath('/tmp/raycrafter-demo/parts/4f relay.raycrafter-part')
In [63]: relay.user_parts()
Out[63]: ['4f relay']
In [64]: other = Bench(empty=True)
In [65]: [e.front_z_mm for e in other.insert_user_part("4f relay", front_z_mm=60)]
Out[65]: [60.0, 260.0]
User parts are small files in your own application-data folder (this page’s examples use a temporary one), so
they are shared between designs. flip_assembly turns an assembly round, and split_assembly
dissolves it.
Plössl pairs
make_plossl turns one positive catalogue lens into a Plössl pair: two copies of it facing each other, made
into an assembly.
In [66]: pair = Bench(empty=True)
In [67]: pair.add_lens("AC254-100-A");
In [68]: pair.make_plossl(0)
In [69]: [(e.front_z_mm, e.flipped, e.assembly_name) for e in pair.elements]
Out[69]:
[(95.43425661318444, True, 'Plossl pair'),
(102.93425661318444, False, 'Plossl pair')]
In [70]: pair.plot("ray_diagram")

In [71]: pair.split_assembly(0)
In [72]: [e.assembly_name for e in pair.elements]
Out[72]: [None, None]
Apertures and the stop
An aperture is an element like a lens. Without a diameter it is open and blocks nothing. Make it (or a lens) the aperture stop, and the fields can be aimed to fill it.
In [73]: iris_bench = Bench(empty=True)
In [74]: iris_bench.add_paraxial_lens(100, front_z_mm=50);
...: iris_bench.add_paraxial_lens(100, front_z_mm=250);
In [75]: iris = iris_bench.add_aperture(front_z_mm=100, diameter_mm=6)
In [76]: iris.kind, iris.index, iris.clear_diameter_mm
Out[76]: ('aperture', 1, 6.0)
In [77]: iris_bench.add_field(angle_deg=3, colour="#d62728");
In [78]: iris_bench.set_stop(iris.index)
In [79]: iris_bench.set_fields_fill_stop(True)
In [80]: info = iris_bench.stop_info()
In [81]: info.element_index, info.warnings
Out[81]: (1, [])
In [82]: info.fields # what the stop sets for each field
Out[82]:
[{'field_index': 0,
'fills_stop': True,
'diameter_mm': 11.99976,
'offset_mm': 0.0},
{'field_index': 1,
'fills_stop': True,
'diameter_mm': 11.99976,
'offset_mm': -5.24078}]
In [83]: iris_bench.set_image_z(350)
In [84]: iris_bench.plot("ray_diagram")

In [85]: iris_bench.set_aperture(iris.index, diameter_mm=3).clear_diameter_mm
Out[85]: 3.0
Fields (beams)
A field’s diameter, offset, angle and vergence are those at the source plane.
set_field changes only what you pass. add_field copies the selected field, applies your
changes and selects the new one.
In [86]: bench = Bench(empty=True)
In [87]: bench.add_lens("AC254-100-A");
In [88]: bench.set_field(0, diameter_mm=8, wavelength_nm=488)
Out[88]: FieldInfo(index=0, kind='beam', diameter_mm=8.0, angle_deg=0.0, vergence_dioptres=0.0, offset_mm=0.0, height_x_mm=None, height_y_mm=None, numerical_aperture=None, wavelength_nm=488.0, colour='#00c4cc', colour_follows_wavelength=True, selected=True)
In [89]: bench.add_field(angle_deg=2, colour="#d62728");
In [90]: bench.add_field(angle_deg=-3, vergence_dioptres=0, offset_mm=1, colour="wavelength");
In [91]: [(f.index, f.angle_deg, f.offset_mm, f.colour, f.selected) for f in bench.fields]
Out[91]:
[(0, 0.0, 0.0, '#00c4cc', False),
(1, 2.0, 0.0, '#d62728', False),
(2, -3.0, 1.0, '#00c4cc', True)]
In [92]: bench.remove_fields([2])
In [93]: bench.select_field(0)
In [94]: bench.selected_field_index
Out[94]: 0
A colour given by hand switches the design to your own colours. set_colour_rule colours all fields by
"wavelength", "angle", "offset" or "custom", and
set_rays_per_field sets how many rays are drawn.
In [95]: bench.set_colour_rule("angle");
In [96]: bench.set_rays_per_field(7)
In [97]: bench.colour_rule, bench.rays_per_field
Out[97]: ('angle', 7)
Finite objects and distortion
set_finite_object turns every field into a point of an object on the source plane, with a height and a
numerical aperture. new_design(example="Basic microscope") starts from a ready-made one.
In [98]: microscope = Bench(empty=True)
In [99]: microscope.new_design(discard_unsaved=True, example="Basic microscope")
In [100]: [(f.kind, f.height_y_mm, f.numerical_aperture) for f in microscope.fields]
Out[100]: [('object_point', 0.0, 0.25), ('object_point', 0.5, 0.25)]
In [101]: s = microscope.summary()
In [102]: s.magnification, s.chief_ray_image_mm
Out[102]: (-20.0, [(0.0, 0.0), (0.0, -10.0)])
In [103]: microscope.replace_lens(1, "AC254-200-A");
In [104]: microscope.set_field(1, height_y_mm=0.8);
In [105]: microscope.autofocus();
In [106]: d = microscope.distortion()
In [107]: d.magnification, d.max_distortion_percent
Out[107]: (-20.021938843058038, -1.1146752041716144)
In [108]: microscope.plot("grid_distortion")

Focus and summary
autofocus moves the image plane to the smallest RMS spot of the selected field and returns its z.
In [109]: bench.autofocus()
Out[109]: 203.60930995439207
In [110]: bench.summary()
Out[110]: DesignSummary(effective_focal_length_mm=100.0237167175361, back_focal_length_mm=97.12566624756622, magnification=None, f_number=12.502964589692013, transmitted_beam_diameter_mm=8.0, beam_is_clipped=False, image_z_mm=203.60930995439207, rms_spot_radius_um=[0.16311579073165888, 5.152675210834935], airy_radius_um=[7.442710081098185, 7.429725958674667], chief_ray_image_mm=[(0.0, 0.0), (0.0, 3.4922106060286215)])
In [111]: bench.set_image_z(bench.image_z_mm + 0.5)
In [112]: bench.summary().rms_spot_radius_um
Out[112]: [15.223302045830561, 20.165289949348903]
In [113]: bench.autofocus();
Plots
plot(kind) draws one of these figures:
"ray_diagram","spot_diagram","detector""through_focus","focal_rays","mtf","ray_fan","psf""field_curvature","grid_distortion","distortion""footprint","rms_vs_field","vignetting","wavefront_vs_field","back_aperture","pupil_walk""colour_spot","colour_mtf","focal_shift""transmission","dispersion","teaching","image_simulation"
Single-field plots show the selected field, or the one given by field_index. The distortion plots need a
field off the axis. The Analysis plots page says what each one means.
In [114]: bench.plot("ray_diagram")

In [115]: bench.plot("spot_diagram")

In [116]: bench.plot("through_focus")

In [117]: bench.plot("mtf")

In [118]: bench.plot("ray_fan", field_index=1)

In [119]: bench.plot("field_curvature")

Detector
set_detector puts a sensor on the image plane. detector_fractions gives, for each field, the
share of its light that lands on it.
In [120]: bench.set_detector(width_mm=4, height_mm=3)
Out[120]: DetectorInfo(shape='rectangle', diameter_mm=None, width_mm=4.0, height_mm=3.0)
In [121]: bench.set_image_z(bench.image_z_mm + 12)
In [122]: bench.detector_fractions()
Out[122]: [1.0, 0.0]
In [123]: bench.plot("detector")

In [124]: bench.remove_detector()
In [125]: bench.autofocus();
Raw results as NumPy arrays
Each analysis also returns its numbers. Lengths here are in mm unless the name says otherwise.
In [126]: spot = bench.spots()[0]
In [127]: spot.x.shape, spot.rms_radius * 1000 # rays; RMS radius in µm
Out[127]: ((127,), 0.1631157907316844)
In [128]: tf = bench.through_focus()
In [129]: tf.offsets.shape, tf.best_offset, tf.airy_radius
Out[129]: ((161,), 0.000267262796186607, 0.007442710081098185)
In [130]: mtf = bench.mtf()
In [131]: import numpy as np
In [132]: for f in (10, 25, 50): # cycles/mm
...: t = np.interp(f, mtf.frequency, mtf.tangential)
...: s = np.interp(f, mtf.frequency, mtf.sagittal)
...: print(f"{f:3} cyc/mm T = {t:.3f} S = {s:.3f}")
10 cyc/mm T = 0.923 S = 0.923
25 cyc/mm T = 0.807 S = 0.807
50 cyc/mm T = 0.617 S = 0.617
In [133]: fan = bench.ray_fan(field_index=1)
In [134]: fan.pupil.shape, np.nanmax(np.abs(fan.tangential_error))
Out[134]: ((41,), np.float64(0.009526640052142099))
In [135]: curvature = bench.field_curvature()
In [136]: curvature.angles
Out[136]: array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
In [137]: curvature.tangential_shift.round(2)
Out[137]:
array([ 0. , -0.05, -0.21, -0.48, -0.86, -1.34, -1.93, -2.61, -3.4 ,
-4.29, -5.27])
Plot them however you like:
In [138]: from matplotlib.figure import Figure
In [139]: fig = Figure(figsize=(7, 3.5))
...: ax = fig.subplots()
...: for i, name in enumerate(["on axis", "2 deg"]):
...: result = bench.through_focus(field_index=i)
...: ax.plot(result.offsets, result.rms_current * 1000, label=name)
...: ax.set(xlabel="image plane offset (mm)", ylabel="RMS spot radius (µm)")
...: ax.legend()
...: fig

bench.state() returns a copy of the complete design, every surface included, for use with
raycrafter.core.analysis. Changing the copy does not change the bench.
Across the field
These analyses swing the selected field through a range of angles: a beam about the point where it crosses the source plane, or about the aperture stop while the fields fill it. Here a small second lens cuts off tilted beams.
In [140]: wide = Bench(empty=True)
In [141]: wide.add_lens("AC254-100-A");
...: wide.add_lens("AC127-050-A");
...: wide.set_gap(0, 55);
...: wide.set_field(0, diameter_mm=12);
...: wide.autofocus();
In [142]: footprint = wide.footprint(max_angle_deg=3)
In [143]: round(footprint.field_of_view_x_mm, 2), round(footprint.field_of_view_y_mm, 2)
Out[143]: (5.71, 5.71)
In [144]: sweep = wide.rms_vs_field(max_angle_deg=8, points=5)
In [145]: sweep.angles_deg, (sweep.rms_radius * 1000).round(1) # um, one row per wavelength
Out[145]: (array([0., 2., 4., 6., 8.]), array([[ 1.3, 3.3, 8.1, 14.7, 8.5]]))
In [146]: light = wide.vignetting(max_angle_deg=8, points=5)
In [147]: light.transmitted.round(2), light.relative_illumination.round(2)
Out[147]: (array([1. , 1. , 0.98, 0.49, 0.01]), array([1. , 0.92, 0.67, 0.43, 0.19]))
In [148]: [(blocker.name, blocker.element_index) for blocker in light.blockers]
Out[148]: [('AC127-050-A (element 1)', 1)]
In [149]: wide.add_field(angle_deg=8); # plot() sweeps out to the largest field angle
...: wide.select_field(0)
...: wide.plot("vignetting")

Mark a back aperture to look at the beams on one element. The 4f scan system example has one already.
In [150]: scan = Bench(empty=True)
In [151]: scan.new_design(discard_unsaved=True, example="4f scan system")
In [152]: back = scan.back_aperture_footprint()
In [153]: [round(each.fraction_inside, 3) for each in back.field_footprints]
Out[153]: [1.0, 1.0, 1.0]
In [154]: round(back.max_walk_mm, 3) # how far the beam's centre moves as it scans
Out[154]: 0.105
In [155]: scan.plot("back_aperture")

set_back_aperture(element_index) marks an element.
Wavefront and colour
Focus first: the point spread function and Strehl ratio describe the current image plane.
In [156]: singlet = Bench(empty=True)
In [157]: singlet.add_lens("LA1509-A");
In [158]: singlet.set_field(0, diameter_mm=8, wavelength_nm=587.6)
Out[158]: FieldInfo(index=0, kind='beam', diameter_mm=8.0, angle_deg=0.0, vergence_dioptres=0.0, offset_mm=0.0, height_x_mm=None, height_y_mm=None, numerical_aperture=None, wavelength_nm=587.6, colour='#ccb400', colour_follows_wavelength=True, selected=True)
In [159]: singlet.add_field(wavelength_nm=486.1);
...: singlet.add_field(wavelength_nm=656.3);
In [160]: singlet.select_field(0)
...: singlet.autofocus();
In [161]: psf = singlet.psf()
In [162]: round(psf.strehl, 3), round(psf.rms_wavefront_waves, 3), round(psf.airy_radius_um, 2)
Out[162]: (0.983, 0.021, 8.91)
In [163]: singlet.plot("psf")

In [164]: singlet.wavefront_vs_field(max_angle_deg=4, points=5).strehl.round(2)
Out[164]:
array([[0.02, 0.02, 0.02, 0.01, 0.01],
[0.98, 0.99, 0.88, 0.44, 0.14],
[0.21, 0.27, 0.49, 0.73, 0.54]])
In [165]: colour = singlet.polychromatic_spot()
In [166]: round(colour.rms_radius_um, 1), round(colour.lateral_colour_um, 2)
Out[166]: (20.7, 0.0)
In [167]: shift = singlet.focal_shift()
In [168]: shift.design_wavelengths_nm, shift.design_shift_mm.round(3) # best focus from the image plane
Out[168]: ([486.1, 587.6, 656.3], array([-1.055, 0. , 0.476]))
In [169]: singlet.plot("focal_rays")

polychromatic_mtf() gives the MTF for all the wavelengths together, and
rays_through_focus() the rays drawn above.
Collimation, transmission and pulse dispersion
In [170]: expander = Bench(empty=True)
In [171]: expander.new_design(discard_unsaved=True, example="Galilean beam expander")
In [172]: output = expander.collimation()
In [173]: output.is_collimated, round(output.output_diameter_mm, 2), round(output.diameter_ratio, 2)
Out[173]: (True, 10.01, 4.0)
In [174]: pair = Bench(empty=True)
In [175]: pair.add_lens("AC254-100-B");
...: pair.add_lens("AC254-050-B");
...: pair.set_field(0, wavelength_nm=920);
In [176]: transmission = pair.transmission()
In [177]: round(transmission.total, 3), [round(lens.total, 3) for lens in transmission.lenses]
Out[177]: (0.973, [0.987, 0.986])
In [178]: transmission.notes # the assumptions made
Out[178]: ["Coated surfaces are taken to reflect the vendor's published limit on the coating's average (an assumption: a real coating varies with wavelength and angle)"]
In [179]: dispersion = pair.dispersion()
In [180]: round(dispersion.gdd_fs2), round(dispersion.pulse_duration_fs(100), 1) # from 100 fs
Out[180]: (1155, 105.0)
In [181]: pair.plot("dispersion")

transmission_spectrum() and dispersion_spectrum() give both against wavelength.
Image simulation and teaching overlays
image_simulation shows a picture (a chessboard if you give none) as the design images it. It takes a few
seconds, and is geometric: there is no diffraction.
In [182]: singlet.set_field(0, diameter_mm=10);
...: singlet.add_field(angle_deg=12);
...: singlet.select_field(0)
...: singlet.autofocus();
In [183]: simulated = singlet.image_simulation(pixels=200)
In [184]: simulated.shown.shape, round(simulated.half_width_mm, 2), simulated.wavelengths_nm
Out[184]: ((200, 200, 3), 16.28, (656.3, 587.6, 486.1))
In [185]: fig = Figure(figsize=(4, 4))
...: ax = fig.subplots()
...: w, h = simulated.half_width_mm, simulated.half_height_mm
...: ax.imshow(simulated.shown, extent=(-w, w, -h, h))
...: ax.set(xlabel="x (mm)", ylabel="y (mm)")
...: fig

teaching_overlays gives the chief and marginal rays, pupils, cardinal points and focal lengths.
In [186]: singlet.plot("teaching")

Named designs
Keep variants of a design under names, switch between them, and write a page that compares them.
In [187]: bench = Bench(empty=True)
In [188]: bench.add_lens("AC254-100-A");
...: bench.autofocus();
In [189]: bench.save_design("Achromat", note="the starting point")
In [190]: bench.replace_lens(0, "LA1509-A");
...: bench.autofocus();
In [191]: bench.save_design("Singlet")
In [192]: [design.name for design in bench.designs]
Out[192]: ['Achromat', 'Singlet']
In [193]: bench.choose_design("Achromat")
In [194]: bench.elements[0].part_number
Out[194]: 'AC254-100-A'
In [195]: bench.write_comparison("comparison.html") # add open_in_browser=True to view it
Out[195]: PosixPath('/private/tmp/raycrafter-demo/comparison.html')
edit_design renames a design or changes its note, remove_design forgets one, and
design_is_edited says whether the bench has changed since. choose_design discards unkept
changes.
Sweeps
Scripting pays off when you compare many configurations. Which way round should a plano-convex lens go?
In [196]: for part in ("LA1509-A", "AC254-100-A"):
...: test = Bench(empty=True)
...: test.add_lens(part)
...: for _ in range(2):
...: test.autofocus()
...: s = test.summary()
...: print(f"{part:12} flipped={test.elements[0].flipped!s:5} "
...: f"RMS = {s.rms_spot_radius_um[0]:7.2f} µm Airy = {s.airy_radius_um[0]:.2f} µm")
...: test.flip_lens(0)
LA1509-A flipped=False RMS = 2.75 µm Airy = 6.71 µm
LA1509-A flipped=True RMS = 10.93 µm Airy = 6.68 µm
AC254-100-A flipped=False RMS = 0.42 µm Airy = 6.77 µm
AC254-100-A flipped=True RMS = 6.38 µm Airy = 6.75 µm
How does spot size grow with beam diameter?
In [197]: diameters = np.arange(2, 21, 2)
In [198]: curves = {}
...: for part in ("LA1509-A", "AC254-100-A"):
...: test = Bench(empty=True)
...: test.add_lens(part)
...: rms = []
...: for d in diameters:
...: test.set_field(0, diameter_mm=d)
...: test.autofocus()
...: rms.append(test.summary().rms_spot_radius_um[0])
...: curves[part] = rms
In [199]: fig = Figure(figsize=(7, 3.5))
...: ax = fig.subplots()
...: for label, rms in curves.items():
...: ax.semilogy(diameters, rms, "o-", label=label)
...: ax.set(xlabel="beam diameter (mm)", ylabel="RMS spot radius at best focus (µm)")
...: ax.legend()
...: fig

Drive the open window
Start RayCrafter (raycrafter in another terminal), then use Bench.connect(). The methods are
the same, but each edit happens in the window and it redraws. The script also sees changes you make by hand. The link
only listens on your own computer. It is off if RayCrafter was started with --no-agent-link.
In [200]: live = Bench.connect()
In [201]: live
Out[201]: <Bench (connected to the RayCrafter window): 1 lens, 1 field, image at 307.2 mm>
In [202]: live.is_connected
Out[202]: True
In [203]: live.new_design(discard_unsaved=True)
In [204]: live.add_lens("AC254-100-A");
...: live.add_lens("AC254-050-A", front_z_mm=180);
...: live.add_field(angle_deg=1.5, colour="#d62728");
...: live.select_field(0)
...: live.autofocus()
Out[204]: 200.7462817400462

Move a lens from the script and the window follows:
In [205]: live.move_element(1, front_z_mm=140);
In [206]: live.autofocus()
Out[206]: 172.7394436062333

Which index is which?
The Bench list in the window (View → View bench) shows every element and field with the index the API uses. Selecting a row highlights it in the side view. Here element 1 is selected.
In [207]: [(e.index, e.part_number) for e in live.elements]
Out[207]: [(0, 'AC254-100-A'), (1, 'AC254-050-A')]


Files and reports
A project file (.raycrafter) keeps the whole design. Save to one to keep your work.
In [208]: bench = Bench(empty=True)
In [209]: bench.add_lens("AC254-100-A");
...: bench.add_lens("AC254-050-A", front_z_mm=250);
...: bench.add_field(angle_deg=1);
In [210]: bench.has_unsaved_changes
Out[210]: True
In [211]: bench.save_project("reducer")
Out[211]: PosixPath('/private/tmp/raycrafter-demo/reducer.raycrafter')
In [212]: bench.has_unsaved_changes
Out[212]: False
In [213]: again = Bench.from_project("reducer.raycrafter")
In [214]: len(again.elements), len(again.fields)
Out[214]: (2, 2)
Zemax .zmx files are for exchanging designs with other programs. Exporting one does not count as saving,
because it cannot hold everything. load_zmx imports a file and returns a
list of notes on anything RayCrafter simplified (see how lenses differ from Zemax). The
design remembers which file it was imported from.
In [215]: bench.save_zmx("reducer.zmx")
Out[215]: PosixPath('/private/tmp/raycrafter-demo/reducer.zmx')
In [216]: imported = Bench.from_zmx("reducer.zmx")
In [217]: imported.imported_from, imported.modified_since_import
Out[217]: ('reducer.zmx', False)
In [218]: imported.flip_lens(0);
In [219]: imported.modified_since_import
Out[219]: True
In [220]: notes = imported.load_zmx("reducer.zmx", discard_unsaved=True)
In [221]: notes
Out[221]: []
In [222]: imported.save_project("imported.raycrafter", forget_import=True) # drop the original ZMX
Out[222]: PosixPath('/private/tmp/raycrafter-demo/imported.raycrafter')
In [223]: imported.imported_from
In [224]: bench.write_report("design.html") # add open_in_browser=True to view it
Out[224]: PosixPath('/private/tmp/raycrafter-demo/design.html')
STEP files for CAD
save_step writes the lenses as solids, with rays if you ask for rings of them. It needs
pip install "raycrafter[cad]".
In [225]: step = again.save_step("reducer.step", ray_rings=1)
In [226]: step.solid_count, step.ray_count, step.left_out
Out[226]: (4, 14, [])
Errors
A request that makes no sense raises ValueError with an explanation. Bench.connect() raises
ConnectionError if no window answers.
In [227]: bench.add_lens("AC999-000-Z") # raises
ValueError: Unknown part number 'AC999-000-Z'; use search_lenses to find one
In [228]: bench.flip_lens(7) # raises
ValueError: There is no element 7; the bench has 2 element(s)
In [229]: bench.lock_gap(1); # the gap to the image plane
In [230]: bench.autofocus() # raises
ValueError: The gap to the image plane is locked: unlock it to focus
In [231]: bench.new_design() # raises
ValueError: The design has unsaved changes. Call save_project first, or pass discard_unsaved=true to throw them away.
Reference
The full docstrings are in
raycrafter/api.py
and, next to it, design_files.py and the *_methods.py files. Or type
bench.add_lens? in IPython. Arguments in [brackets] are optional.
| Create | |
|---|---|
Bench([empty]) | Headless bench |
Bench.connect([endpoint_path]) | Drive the open window |
Bench.from_project(file_path) | Headless bench from a project file |
Bench.from_zmx(file_path) | Headless bench from a Zemax file |
| Read | |
catalog, search_lenses([query, min_focal_length_mm, max_focal_length_mm, min_diameter_mm, category]) | Catalogue entries |
elements, fields | Lists of ElementInfo, FieldInfo |
image_z_mm, selected_field_index | Image plane, selected field |
source_z_mm, source_gap_mm, source_gap_locked | Source plane |
colour_rule, rays_per_field | How fields are drawn |
stop_index, stop_info(), detector | Aperture stop, detector |
key_planes() | Focal points and foci |
designs, design_is_edited | Named designs |
is_connected, has_unsaved_changes | Booleans |
project_path, imported_from, modified_since_import | Where the design came from |
state() | Copy of the whole design |
| Lenses and apertures | |
add_lens(part_number, [front_z_mm]) | Add a catalogue lens |
add_paraxial_lens(focal_length_mm, [front_z_mm, diameter_mm]) | Add an ideal thin lens |
add_aperture([front_z_mm, diameter_mm]) | Add an aperture (open without a diameter) |
set_aperture(element_index, [diameter_mm]) | Set its diameter, or open it |
move_element(element_index, front_z_mm) | Move, as by dragging |
move_element_to(element_index, front_z_mm) | Put exactly there, or refuse |
replace_lens(element_index, [part_number, paraxial_focal_length_mm, plossl_pair]) | Swap a lens in place |
flip_lens(element_index), delete_element(element_index) | Turn round, remove |
| Gaps and source plane | |
set_gap(element_index, gap_mm) | Set the gap behind an element |
lock_gap(element_index, [locked]) | Lock or unlock it |
optimise_gap(element_index, [goal, apply, lock, flip_if_better, measure_after_element_index]) | Collimate or focus by setting a gap |
set_source_gap(gap_mm), lock_source_gap([locked]) | Gap in front of the first lens |
set_source_z(source_z_mm) | Move the source plane |
| Assemblies and user parts | |
make_assembly(first_element_index, last_element_index, [name]) | Group neighbouring elements |
flip_assembly(element_index), split_assembly(element_index) | Turn round, dissolve |
make_plossl(element_index) | Make a Plössl pair from a lens |
save_user_part(element_index, name, [overwrite]) | Save an assembly |
user_parts(), insert_user_part(name, front_z_mm) | List, insert |
| Fields, stop, detector and image plane | |
set_field(field_index, [diameter_mm, angle_deg, vergence_dioptres, offset_mm, wavelength_nm, colour, height_x_mm, height_y_mm, numerical_aperture]) | Change a field |
add_field([...]) | Copy the selected field, with changes |
remove_fields(field_indices), select_field(field_index) | Remove, select |
set_finite_object([finite]) | Object points, or beams |
set_colour_rule(rule), set_rays_per_field(ray_count) | Colours, rays drawn |
set_stop([element_index]), set_fields_fill_stop([fill]) | Choose the stop, fill it |
set_detector([shape, diameter_mm, width_mm, height_mm]), remove_detector() | Sensor on the image plane |
set_image_z(image_z_mm), autofocus() | Place the image plane |
| Analyses | |
summary() | DesignSummary |
spots() | One spot result per field |
through_focus([field_index]), mtf([field_index]), ray_fan([field_index]), field_curvature([field_index]) | Result arrays |
distortion([field_index, reference, grid_points, mapping]) | Grid distortion |
rays_through_focus([field_index]) | Rays near the image plane, by wavelength |
footprint(...), rms_vs_field(...), vignetting(...),
wavefront_vs_field(...) | Across the field: [field_index, max_angle_deg, points] |
set_back_aperture(element_index), back_aperture_footprint([element_index, ...]) | Beams on one element |
psf([field_index]) | Point spread function and Strehl ratio |
polychromatic_spot([field_index]), polychromatic_mtf([field_index]),
focal_shift([field_index, points]) | All wavelengths together |
collimation([field_index]) | The light leaving the last lens |
transmission([field_index]), dispersion([field_index]) | Glass losses and GDD |
transmission_spectrum([field_index, wavelengths_nm]),
dispersion_spectrum([field_index, wavelengths_nm]) | Both against wavelength |
image_simulation([picture, width, wavelengths_nm, pixels, field_index]) | A picture as imaged |
teaching_overlays([field_index]) | Chief and marginal rays, pupils, cardinal points |
| Named designs | |
save_design(name, [note, overwrite]), choose_design(name) | Keep, put on the bench |
edit_design(name, [new_name, note]), remove_design(name) | Rename, forget |
write_comparison(file_path, [open_in_browser]) | Side-by-side HTML page |
detector_fractions() | Share of each field’s light on the detector |
plot(kind, [field_index]) | matplotlib Figure |
| Files | |
new_design([discard_unsaved, example]) | Start again, or from an example |
save_project([file_path, forget_import]) | Save the whole design |
load_project(file_path, [discard_unsaved]) | Open a project |
load_zmx(file_path, [discard_unsaved]), save_zmx(file_path) | Import, export Zemax files |
write_report(file_path, [open_in_browser]) | HTML report |
save_step(file_path, [ray_rings]) | STEP file for CAD |