ray-tracing-shapely
A 2D optical analysis and design environment in Python, built on Shapely for geometry. It began as a translation of a JavaScript interactive simulator and grew into something with a different purpose.
What it is for
Most 2D optics tools let you watch rays. This one lets you ask questions about them afterwards, and lets you design a surface from what you want the light to do.
Every traced ray keeps its lineage — a parent, a unique identity, the surfaces it met and what happened at each one. That turns a simulation from a picture into a record you can query: which paths reach the detector, how much energy each carries, where two designs begin to differ, which rays are trapped by repeated total internal reflection. Runs are stored and compared, so "did that change help?" is a question with an answer rather than an impression.
On top of that sit layers the original simulator does not have:
- Ray lineage as a graph — parent/child tracking, structural path signatures, bidirectional tracing that connects a forward tree from the sources to a backward tree from the detector.
- Nonimaging design — CPC-family concentrators (DTIRC, angle transformer, RXI) and Miñano–Benítez Simultaneous Multiple Surface profile construction (RR / RX / XR / RXI), on a reusable plane-curve toolbox. Surfaces are built from optical requirements, not from vertices typed in by hand.
- Lenses and aspheres — labelled singlets, LED collimators (a TIR lens and a Fresnel lens) and exact even aspheres as glass edges, with the coefficients in Zemax's and Optiland's order. A lens face measured by a profilometer is read from its DXF and fitted with its vertex and tilt. The fit reports which of its numbers the data do not separately determine, and becomes two models of the lens, fitted and as measured.
- Light sources and measured LEDs — a source described once, built in 2D
and in 3D, and stored with the element it lights in
profile.json. An LED's rayfile (IES TM-25) is read, drawn as a radiation pattern, and sliced into the 2D plane, with the share of its light a 2D section cannot carry stated. - Light on a plane — the irradiance map, and the 2D line profile, of the light that leaves an optic.
- Radiometry and eye safety — unit-checked physical quantities, and exposure-limit routines for IEC 60825-1 (lasers) and IEC 62471 (lamps and LEDs), run as explicit state machines rather than nested conditionals.
- An agentic surface — the whole query layer is exposed as tools a language model can call, sharing one live kernel with the human at the notebook. Several runs are held at once as named contexts, a saved run is reloaded by reference, and a package built on the library adds tools of its own beside the core's.
- Designs as blocks and graphs — the steps from a rayfile to a risk group (slice a rayfile, make a source, place a collimator and a detector, trace, read, weight for a hazard, classify) as typed blocks, each input with its unit. An agent builds with six generic tools over them, and hands its work back as a graph. A person draws the same graph on a canvas, runs only what an edit made stale, and compiles it to the notebook that runs it.
- Long runs, off the notebook — a procedure is a flow: a fixed diagram whose every step is recorded, so a run that stops can be read back. Its long jobs go to local processes or to Modal's serverless containers, each with an estimate of its time and cost before it starts, and a local dashboard shows what is running and what it has cost. A targeted re-simulation of the paths that matter, cut into chunks, runs this way and gives the run the kernel would have given.
- Run persistence — parameter sweeps, stored results, cross-run comparison.
If you want an interactive simulator with a gallery of worked scenes, the upstream Ray Optics Simulation is better. This is more an analytical tool to understand a design.
Install
pip install ray-tracing-shapely
The core install stays deliberately small — shapely, numpy, sympy,
svgwrite, networkx. The heavier layers are extras, so you only pay for
what you use:
pip install "ray-tracing-shapely[radiometry]" # unit-checked quantities (pint)
pip install "ray-tracing-shapely[flows]" # observable step-by-step procedures (transitions)
pip install "ray-tracing-shapely[eye-safety]" # IEC 60825-1 / IEC 62471
pip install "ray-tracing-shapely[agentic]" # the MCP tool surface
pip install "ray-tracing-shapely[modal]" # flows' jobs on Modal (the Modal client)
pip install "ray-tracing-shapely[widgets]" # a flow's form, the scene builder and the graph editor in a notebook cell (anywidget)
pip install "ray-tracing-shapely[web]" # the same three, as pages for hosts without widgets (solveit)
pip install "ray-tracing-shapely[notebook]" # running the example notebooks (jupyterlab, papermill)
pip install "ray-tracing-shapely[all]" # everything
Python 3.11 or newer. The blocks and the graph editor read quantities with
their units, so widgets and web bring radiometry with them.
Thirty seconds
from ray_tracing_shapely.core.scene import Scene
from ray_tracing_shapely.core.scene_objs import Glass, SingleRay
from ray_tracing_shapely.core.simulator import Simulator
scene = Scene()
scene.color_mode = 'linear'
prism = Glass(scene)
prism.path = [
{'x': 100, 'y': 50, 'arc': False},
{'x': 200, 'y': 50, 'arc': False},
{'x': 150, 'y': 150, 'arc': False},
]
prism.refIndex = 1.5
scene.add_object(prism)
ray = SingleRay(scene)
ray.p1 = {'x': 50, 'y': 100}
ray.p2 = {'x': 100, 'y': 100}
scene.add_object(ray)
segments = Simulator(scene, max_rays=1000).run()
print(f"Traced {len(segments)} ray segments") # Traced 16 ray segments
Sixteen segments from one incident ray: it refracts into the glass, reflects
internally, and splits at each surface it meets. Render the result as SVG with
SVGRenderer, and every element it draws carries the identity of the ray or
object that produced it, so a diagram can be clicked back to the simulation
that made it.
Drawing a scene, filling in a flow
In a notebook (VS Code, JupyterLab, Colab), with the widgets extra:
from ray_tracing_shapely.builder import scene_builder
from ray_tracing_shapely.flows.widget import flow_form
scene_builder(path="my.scene.json") # draw and edit a scene with the pointer; Save writes the file
flow_form(flow) # a flow's questions as a form, answered in the cell
The scene builder places primitives from a palette and designed elements from a form of their arguments, edits by dragging, as the web Ray Optics Simulation does, and traces after every change. It saves a scene file, which a parameter study or an agent reads, and opens and exports the web simulator's own files. The scene's elements are listed as a tree beside the canvas, and Pan makes every drag move the view. Every rule runs in Python; the page only draws.
from ray_tracing_shapely.graph import graph_editor
graph_editor(path="design.graph.json") # blocks joined by wires; Compile writes the notebook that runs them
The graph editor draws a design as blocks joined by wires: a rayfile slice feeds a source, the source and a detector feed a scene, the scene a trace, and so on to a risk group. A wire of the wrong type is refused as it is drawn, with the reason. The graph is saved as a small file and compiled to a notebook, one cell per block; the graph runs only as that notebook.
Run runs that notebook's cells in the editor and keeps each block's
result, so after an edit only the blocks it made stale run again; each block
shows whether it is fresh, stale, running or failed, and a fresh block's
values. A trace estimated at over a minute goes to a worker process, given
one (graph_editor(runner=GraphRunner(executor=...))), and is refused with
its estimate otherwise.
The blocks are also what an agent builds with. With the agentic extra,
blocks.agentic.register() adds six tools to the MCP server: list the
blocks, describe one, run one (its outputs kept under handles, wired into the
next block as {"ref": "v3"}), read or list the kept values, and
block_graph, which writes the agent's work as a graph file. The person opens
that file in the graph editor, or compiles it.
In solveit
solveit is Answer.AI's web environment for working on code alongside an AI. You work in dialogs: one page that mixes code cells, notes and prompts, where the AI sees what came before and runs code in the same Python process you do. Each instance is a persistent server of your own, with a terminal, files and git, and an app run there can be served at the instance's public URL. To reach it, sign up at solve.it.com: joining is free, and use (compute and the AI's tokens) is billed as you go. Then open a dialog and install the package in a code cell:
!pip install "ray-tracing-shapely[web]"
A dialog runs Jupyter "except for ipywidgets", so the widgets above do not
show there. With the web extra, the same views are served as pages from a
FastHTML app in the dialog, and shown in an iframe:
from fasthtml.common import FastHTML
from fasthtml.jupyter import JupyUvi
from ray_tracing_shapely.web import Views
app = FastHTML()
views = Views(base_url="https://<your instance's public URL>")
views.mount(app) # the pages' routes, under /rts
server = JupyUvi(app) # serves the app on port 8000
views.embed(views.builder(path="my.scene.json")) # the scene builder
views.embed(views.flow(flow)) # a flow's form
views.embed(views.graph(path="design.graph.json")) # the graph editor
base_url is the address at which the instance serves the app on port 8000,
the public URL solveit gives the instance; the iframe loads the pages from
there. The pages and their routes are tested in a browser against a local
server, and the scene builder has been used by hand in a solveit dialog.
Outside solveit, views.serve() runs the pages on a local server for any
browser.
Documentation
The code is documented in two layers, both shipped with the package:
dev_doc/concepts/— why the code has the shape it has. Thirty-eight numbered concepts, each stating one claim and the evidence for it, written for a reader who wants to understand the design rather than just call it.dev_doc/architecture/— what is true now: a component map, a port register, and contracts stating what each boundary assumes and guarantees.
Docstrings cite both, so a question that starts in the code has somewhere to go.
Citing
If you use this software, please cite both this project and the Ray Optics
Simulation project it is in part translated from. CITATION.cff carries the
metadata for both; GitHub will format it for you from the Cite this
repository link.
This project: doi:10.5281/zenodo.23991020 — that is the concept DOI and always resolves to the latest release. Each release also has its own DOI, which is what to cite if you need to pin the exact version a result came from.
Upstream: doi:10.5281/zenodo.6386611.
Licence and attribution
Apache-2.0. See LICENSE.txt and NOTICE.txt.
This project began as a translation of the Ray Optics Simulation JavaScript project (Copyright 2024 its authors and contributors, Apache-2.0, doi:10.5281/zenodo.6386611), and has grown a great deal of new work on top of it.
Of this distribution's 283 source files, 37 are translations of
that project — the ray-tracing engine and its scene objects — and 246
were written for this project: the analysis layer, the nonimaging design
methods, the radiometric and photobiological layers, the agentic surface,
and the tests and examples. Every file says which it is in its own header,
and NOTICE.txt lists the translated set.
If you use this software please cite both, per CITATION.cff.
Status
Early development: the translation of the original simulator is not complete, and the API is not yet stable. Issues and descriptions of what you are trying to do are the most useful contribution right now .
Metadata
Release files for ray-tracing-shapely 0.4.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ray_tracing_shapely-0.4.1.tar.gz | 1.1 MB | With provenance | Details for ray_tracing_shapely-0.4.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ray_tracing_shapely-0.4.1-py3-none-any.whl | Python 3 | none | any | Details for ray_tracing_shapely-0.4.1-py3-none-any.whl |
Total release size: 2.4 MB
Release files / ray_tracing_shapely-0.4.1.tar.gz
| Download URL | ray_tracing_shapely-0.4.1.tar.gz |
|---|---|
| Size | 1.1 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
dcfb590a0a37d1960b100f809da382658ae23741ced03dc2149f018867b1ea33
|
|
BLAKE2b-256 checksum How to use checksums |
78d5cce6e32ee63c48670df8946dc7798362e1fc1387f9922824c015aa4d5c5f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.
Transparency logRelease files / ray_tracing_shapely-0.4.1-py3-none-any.whl
| Download URL | ray_tracing_shapely-0.4.1-py3-none-any.whl |
|---|---|
| Size | 1.3 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
8c8738c32fe8630c835037ee6da3d2fd6796d636fd516a58f2b2292b3d06116a
|
|
BLAKE2b-256 checksum How to use checksums |
6a829e0643f52ca92a34ba61ea38be32875db2d0a06524c87769c1023fd75c0f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.
Transparency logSecurity for ray-tracing-shapely 0.4.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for ray_tracing_shapely-0.4.1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.