Metadata-Version: 2.4
Name: ray-tracing-shapely
Version: 0.4.2
Summary: Python ray tracing library using Shapely for computational geometry
Author: ray-tracing-shapely authors and contributors
Author-email: Michele Benetti <michele@tiberavon.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/tiberavon/ray-tracing-shapely
Project-URL: Repository, https://github.com/tiberavon/ray-tracing-shapely
Project-URL: Documentation, https://github.com/tiberavon/ray-tracing-shapely#readme
Keywords: ray-tracing,optics,simulation,shapely,physics
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: shapely>=2.0.0
Requires-Dist: sympy>=1.12
Requires-Dist: numpy>=1.23.2
Requires-Dist: svgwrite>=1.4.0
Requires-Dist: networkx>=3.0
Provides-Extra: radiometry
Requires-Dist: pint>=0.24; extra == "radiometry"
Provides-Extra: flows
Requires-Dist: transitions>=0.9; extra == "flows"
Requires-Dist: graphviz>=0.20; extra == "flows"
Provides-Extra: eye-safety
Requires-Dist: ray-tracing-shapely[flows,radiometry]; extra == "eye-safety"
Provides-Extra: agentic
Requires-Dist: mcp<2,>=1.2; extra == "agentic"
Provides-Extra: widgets
Requires-Dist: ray-tracing-shapely[flows,radiometry]; extra == "widgets"
Requires-Dist: anywidget>=0.9; extra == "widgets"
Provides-Extra: web
Requires-Dist: ray-tracing-shapely[flows,radiometry]; extra == "web"
Requires-Dist: starlette>=0.37; extra == "web"
Requires-Dist: uvicorn>=0.23; extra == "web"
Provides-Extra: modal
Requires-Dist: ray-tracing-shapely[flows]; extra == "modal"
Requires-Dist: modal>=1.6; extra == "modal"
Provides-Extra: notebook
Requires-Dist: jupyterlab; extra == "notebook"
Requires-Dist: papermill; extra == "notebook"
Requires-Dist: matplotlib; extra == "notebook"
Provides-Extra: all
Requires-Dist: ray-tracing-shapely[agentic,eye-safety,flows,modal,notebook,radiometry,web,widgets]; extra == "all"
Provides-Extra: test
Requires-Dist: ray-tracing-shapely[agentic,eye-safety,flows,radiometry,web,widgets]; extra == "test"
Requires-Dist: pytest>=7.0.0; extra == "test"
Requires-Dist: httpx>=0.24; extra == "test"
Provides-Extra: dev
Requires-Dist: ray-tracing-shapely[all]; extra == "dev"
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"

# ray-tracing-shapely

[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.23991020.svg)](https://doi.org/10.5281/zenodo.23991020)

A 2D optical **analysis and design** environment in Python, built on
[Shapely](https://shapely.readthedocs.io/) 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](https://github.com/ricktu288/ray-optics) is
better. This is more an analytical tool to understand a design.

## Install

```bash
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:

```bash
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

```python
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:

```python
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.

```python
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](https://solve.it.com) 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](https://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:

```python
!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:

```python
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](https://doi.org/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](https://doi.org/10.5281/zenodo.6386611).

## Licence and attribution

Apache-2.0. See `LICENSE.txt` and `NOTICE.txt`.

<!-- attribution:begin -- generated by dev_doc/tools/attribution.py, do not edit -->
This project began as a translation of the
[Ray Optics Simulation](https://github.com/ricktu288/ray-optics) JavaScript project
(Copyright 2024 its authors and contributors, Apache-2.0,
[doi:10.5281/zenodo.6386611](https://doi.org/10.5281/zenodo.6386611)), and has grown a
great deal of new work on top of it.

Of this distribution's 287 source files, **37 are translations** of
that project — the ray-tracing engine and its scene objects — and **250
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`.
<!-- attribution:end -->

## 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 .
