Skip to content

Draw optics for CAD: layers, units, vertex frames, substrates and sparse rays in DXF - #303

Open
jacobdparker wants to merge 3 commits into
mainfrom
feature/dxf-cad-export
Open

jacobdparker wants to merge 3 commits into
mainfrom
feature/dxf-cad-export

Conversation

@jacobdparker

Copy link
Copy Markdown
Contributor

Makes to_dxf produce a drawing that can be used in CAD to lay out mounts for the optics: each optic is drawn on its own layers, the drawing carries its units, and the frame of each optic and the back of its substrate are drawn too. We tested it by importing the ESIS-II design into the full SolidWorks assembly.

What changed

File format

  • Drawings are written as a full ezdxf R2010 document instead of with r12writer.
  • $INSUNITS is set from the unit argument, so CAD places the drawing at true size without being told the units.

Layers

  • Each surface draws on its own layers: <name>_clear, <name>_mechanical, <name>_substrate and <name>_vertex.
  • A surface that stands for several, such as the channels of an instrument, draws each on its own layers, like grating_channel0_clear. The rays through each channel do the same, like rays_channel0.
  • Surfaces with a duplicate name, or no name, get their index in the system appended.

Apertures

  • Apertures are drawn as closed 3D polylines.
  • Their points are lifted onto the sag by sag.intercept along +z, not by sag(position). The old way put the edges at the wrong height whenever the sag had its own piston or tilt (sag.transformation).
  • Aperture.plot had the same bug and now uses the same lift.

Substrate

  • When a surface's material has a substrate, the drawing includes the substrate's back face. It lies thickness behind the vertex along the sag's axis, on the side away from the light.
  • Edge lines join the front corners of the aperture to the back face.

Vertex frame

  • At each sag vertex the drawing has a POINT and the sag's x/y/z axes as red, green and blue LINEs, each length_axes long.
  • This is the datum frame that a mount can be dimensioned from.

Rays

  • rays=True (the default) draws every ray that passes the system, as before.
  • rays=False leaves the rays out.
  • rays="sparse" draws just enough rays to show the beam path. At each wavelength and channel, those are the rays through the middle and the four edges of the field of view, each at the middle of the beam and at eight points around its edge.
  • The sparse edges are found from where the rays that pass the whole system cross the field stop and the pupil stop, in each stop's own frame. The choice doesn't depend on how the grid is laid out (normalized, absolute or polar) or on the shape of the stops.
  • The trace for a drawing skips the efficiency calculation, since only the ray paths are drawn.

Behaviour changes

  • Rays from a system with channels or another axis of its own now go on rays_<axis><i>; before, they all went on rays. A system without such axes still uses rays.
  • The DXF bytes now include a timestamp and GUIDs, so the nominal test compares the drawn entities instead of the file bytes.

Testing

  • The full suite passes locally: 29,192 passed, 350 skipped, 20 xfailed. ruff and black are clean.
  • New tests:
    • apertures and the substrate on a pistoned, tilted sag, both in the DXF and in plot;
    • the vertex frame, its axes and colors;
    • per-channel layers;
    • the units header;
    • rays set to True, False and "sparse" on every sequential test system;
    • per-channel ray layers;
    • the sparse picks on a square grid.
  • The new tests for the lift fail with the old sag(position) lift.
  • ESIS-II design:
    • Without rays, the export takes 0.4 s and has 172 entities on 71 layers.
    • With rays="sparse" it has 480 rays. Every one is in the full trace, and together they span 92–100% of the full beam on every surface.
    • The full trace has 49,556 rays and takes about the same time as before (30 s).
  • SolidWorks:
    • The drawing was rebuilt in SolidWorks as one 3D sketch per layer.
    • The grating frames match the axes and radius of the parts in the assembly.
    • The SolidWorks DXF import into a part sketch flattens 3D entities into 2D. The import wizard's 3D-curves option, or building sketches through the API, keeps them 3D.

🤖 Generated with Claude Code

jacobdparker and others added 3 commits December 3, 2026 13:17
… DXF

Write a full DXF document instead of an R12 stream, so the header gives
the units and each surface is drawn on its own layers: its clear and
mechanical apertures as closed 3D polylines, the back of its substrate a
thickness behind the vertex with edges joining it to the surface, and the
vertex of its sag with its axes, so a part can be placed and clocked
against it in a CAD program.

Lift the edges of the apertures onto the sag by intercepting it along z.
Using the height the sag gives in its own coordinates put the edges off
the sag whenever the sag was pistoned or tilted with respect to the
surface.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A surface which stands for several, like the channels of an instrument,
now draws each on layers named after its index, so each can be picked
out on its own in a CAD program. `to_dxf` passes its keyword arguments
on, so `rays=False` leaves the rays out of the drawing of a sequential
system, which takes a drawing of the ESIS-II optics from 24 s and 50 000
polylines to under a second and 172 entities.

Plot the apertures and the substrate on the sag the same way the DXF
drawing does: the plot had the same error when the sag was pistoned or
tilted with respect to the surface. The depth and the back of the
substrate are now shared between the two.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ch channel its own

`to_dxf(..., rays="sparse")` draws, at each wavelength and through each
index of the system along its own axes, the rays through the middle and
the four edges of the field of view, each at the middle of the beam and
at eight points around its edge. The edges are found from where the rays
that pass the whole system cross the field stop and the pupil stop, in
each stop's own coordinates, so the choice does not depend on how the
grid is laid out (normalized, absolute or polar) or on the shape of the
stops. For the ESIS-II design that is 480 rays instead of 49,556, which
span 92-100% of the full beam across every surface.

The rays through each channel are now drawn on a layer of their own,
like `rays_channel0`, as the surfaces are, and are traced without their
intensity, which a drawing does not need.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Dec 5, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.11321% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 99.94%. Comparing base (7e70955) to head (e3fa0e2).

Files with missing lines Patch % Lines
optika/surfaces.py 95.55% 4 Missing ⚠️
optika/systems/_sequential.py 97.53% 2 Missing ⚠️
optika/mixins.py 96.96% 1 Missing ⚠️
optika/rays/_ray_vectors.py 95.23% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##              main     #303      +/-   ##
===========================================
- Coverage   100.00%   99.94%   -0.06%     
===========================================
  Files          142      142              
  Lines        14059    14436     +377     
===========================================
+ Hits         14059    14428     +369     
- Misses           0        8       +8     
Flag Coverage Δ
unittests 99.94% <98.11%> (-0.06%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@roytsmart roytsmart left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Jake, this makes the drawing far more usable for laying out mounts. The switch from sag(position) to sag.intercept along +z is also a real bug fix for Aperture.plot, not just the DXF.

I read the whole diff and checked a few things against the code:

  • Nothing else in the workspace overrides _write_to_dxf (only the legacy kgpy and FURST code use r12writer, independently of optika), so changing the writer from R12FastStreamWriter to a Modelspace breaks nothing downstream.
  • sag.normal and sag.intercept both take positions in the surface's frame, so _lift and the sign in _depth_substrate are right. The spherical intercept is closed form, so points that start behind z = 0 are handled.

Comments are inline. The first (axes in _where_rays_sparse) is a quick fix and the second (which frame the substrate is in) is a question; the rest are minor. None of it is a problem with the approach.

One more minor point, not on a changed line: the existing AbstractTestDxfWritable.test_to_dxf still writes test_dwg.dxf into the working directory, so it races with itself under pytest -n. The new tests already use tmp_path, so this would be a good time to move that one too.

# The axes along which the field and the pupil vary, which do not
# include the axes they share with the wavelength or with the system.
axes_other = set(na.shape(grid.wavelength)) | set(system.shape)
axes_field = [a for a in na.shape(grid.field) if a not in axes_other]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This works out the field and pupil axes from the shapes of the grid, but the system already declares them: system.axis_wavelength_, system.axis_field_ and system.axis_pupil_ respect an explicit axis_field / axis_pupil. When those are set explicitly and the field grid carries one more axis, this treats that axis as part of the field and picks five field points across the combined axes, where the rest of the system treats it as an axis of its own.

Using the normalized properties would keep the two in step, e.g.

axes_field = [a for a in system.axis_field_ if a in shape]
axes_pupil = [a for a in system.axis_pupil_ if a in shape]

with everything else falling into axes_rest as now.

Comment thread optika/surfaces.py
return -np.sign(normal.z) * thickness


def _behind(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This moves the back of the substrate from the surface's frame to the sag's frame, and plot changes with the DXF. On main, _plot_substrate put the back thickness behind the surface origin, perpendicular to the surface's z axis. Now it is thickness behind the sag's vertex, perpendicular to the sag's axis.

For a small piston or tilt the two agree, but _surface_dxf in the tests describes its transformed sag as "an off-axis segment of a parent surface". For a real off-axis segment the sag's vertex is the parent's vertex, which can be well off the part. The back would then be drawn behind a point that is not on the optic, square to the parent's axis rather than the part's. No ESIS sag has a transformation, so the SolidWorks check doesn't exercise this.

Which frame is the substrate thickness meant to be in? If it is the part's, keeping the back in the surface's frame (and only lifting the front onto the sag) would cover both cases.

Comment thread optika/mixins.py
Comment on lines +439 to +440
length_axes: u.Quantity = 10 * u.mm,
**kwargs,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since every _write_to_dxf takes **kwargs, a misspelled option is dropped without a word: system.to_dxf(file, u.mm, ray="sparse") draws all ~50k rays, and surface.to_dxf(..., rays=False) does nothing. length_axes likewise sits on the to_dxf of apertures and rays, where it has no effect.

Would it be clearer to give the sequential system (and the surfaces) their own to_dxf with rays and length_axes as explicit arguments, so that each shows up in the signature and docs of the objects it applies to?

Comment thread optika/surfaces.py
close=True,
)

vertices = getattr(aperture, "vertices", None)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: an aperture without vertices (a circle) gets the back face here but no edge lines, while _plot_substrate walls a circle from the samples of its wire. Probably fine for CAD, since a circle extrudes on its own; just noting that the two differ.

Comment thread optika/mixins.py
)


_DXF_UNITS = {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: $INSUNITS also has codes for Å (11), decameters (15), hectometers (16), gigameters (17), AU (18), light years (19) and parsecs (20), which currently fall back to unitless. ezdxf.enums.InsertUnits lists them all, if you'd rather not keep the table by hand.

without_rays = test_mixins.dxf_entities(without_rays)
sparse = test_mixins.dxf_entities(sparse)

def is_ray(e) -> bool:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: e is unannotated here, as is file in _dxf_layer in test_surfaces.py.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants