Metadata-Version: 2.4
Name: optical-ray-collector
Version: 2.0.0
Summary: Scientific package for optical ray tracing simulations.
Home-page: https://github.com/Damzo/optical_ray_collector
Author: Dam-Bè L. DOUTI, Henoc N'GASAMA, Serge DZO
Author-email: ngasamah@gmail.com
License: GPLv3
Project-URL: Source, https://github.com/Damzo/optical_ray_collector
Project-URL: Changelog, https://github.com/Damzo/optical_ray_collector/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/Damzo/optical_ray_collector/issues
Keywords: optics ray-tracing simulation physics
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
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.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: matplotlib>=3.4
Requires-Dist: numpy>=1.21
Requires-Dist: pandas>=1.3
Requires-Dist: scipy>=1.7
Requires-Dist: sympy>=1.9
Requires-Dist: numba>=0.55
Requires-Dist: scikit-learn>=1.0
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: project-url
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# Optical Ray Collector (ORaC)

**Optical Ray Collector** is a Python package for **3D ray tracing of reflective optical collectors** (solar concentrators, mirrors, dishes, troughs, ...).
Surfaces are described as implicit equations `f(x, y, z) = 0` and solved symbolically with [SymPy](https://www.sympy.org/), which gives exact intersection points and surface normals for every ray.

```mermaid
flowchart LR
    G[Geometry<br/>parabolic, cylindrical, plane, custom] --> T[Tracer]
    S[Light source<br/>point, large] --> T
    T --> R[Intersections<br/>reflected rays<br/>terminated rays]
    R --> A[Analysis<br/>plane cuts, 3D density, slope error]
```

---

## Features

### Geometries — `optical_ray_tracer/configurations/geometries/`

| Class | File | Description |
|---|---|---|
| `ParabolicReflector` | `Parabolic.py` | Elliptic paraboloid (focal lengths `f_x`, `f_y`, height `h`), optional rotation |
| `CylindricalReflector` | `Cylindric.py` | Cylindrical trough (`length`, `height`, `thickness`, `orientation`) |
| `RectangularPlaneReflector` | `Plane.py` | Flat rectangular mirror (`dimensions=(width, length)`) |
| `CircularPlaneReflector` | `Plane.py` | Flat circular mirror (`dimensions=(radius,)`) |
| `GivenGeometry` | `given_geometry.py` | Any user-supplied equation `f(x, y, z) = 0` |
| `RingarrayReflector`, `optimizeRingArray` | `ring_array.py` | Ring-array reflector sizing and optimisation (*experimental, not yet traceable*) |

All geometries derive from `Geometry` (`configurations/main.py`) and share the same interface:
`symbolic_equation()`, `boundaries()`, `volume()`, `collection_area()` and `generate_rays_from_source(n_rays, source)`, which returns rays from a source that cover the reflector's aperture.

### Light sources — `optical_ray_tracer/rays/source/`

- `point_source.Source(position_x, position_y, position_z)` — point source; by default placed at `z = 1.5e8` (sun-like, quasi-parallel rays).
- `large_source.Source(position_x, position_y, position_z)` — extended source:
  - `set_geometry("circular" | "elliptical" | "rectangular", ...)`: shape of the emitter, in metres.
  - `geometry.generate_rays_from_source(n, source, n_source_angles=k)` lights the whole geometry with n × k rays. It takes n points covering the reflecting surface, and for each one samples k directions inside the solid angle the source covers as seen from that point. Each ray starts at its own point of the source and lands on its point of the geometry.
  - `set_flux_profile("gaussian" | "lorentzian" | "top-hat", width_x, width_y, theta0, phi0)`: elliptical intensity profile, in degrees.
  - `ray_weights(rays_dict)`: returns `{ray_idx: w}` with w ∈ [0, 1], for `kde_3d_tree(weights=...)`.

### Ray tracer — `optical_ray_tracer/rays/raytracer/`

`Tracer` (`ray_tracer.py`) is the single class to use. Its `tracing` flag picks the engine, each kept in its own module:

| `tracing` | Engine | Best for |
|---|---|---|
| `"symbolic"` (default) | `UncompiledTracer` (`uncompiled_ray_tracer.py`): fully symbolic, solved with SymPy | exact reference, any surface SymPy can solve, tens to hundreds of rays |
| `"compiled"` | `CompiledTracer` (`compiled_ray_tracer.py`): compiled once per surface with `lambdify`, traced with NumPy | 10⁴ rays and more |

Both engines take the same arguments and return the same results; hit points agree to float64 precision. Every method and attribute below is available on `Tracer`, and the engine itself is `tracer.engine`.

- `add_surface(equation, boundaries)` registers a surface (an equation string and its bounding box).
- `add_rays(directions, origins)` registers incident rays (one ray, or lists of rays).
- `trace_new_scene()` computes the nearest intersection of each ray with each surface and the reflected ray. It has two lighting modes:
  - **sequential** (default): surface *i* is lit by the rays reflected by surface *i − 1*, which models an optical train.
  - **parallel**: pass `incident_rays=[rays_0, rays_1, ...]` (one dict per surface) to light every surface on its own.
- Results are stored in:
  - `intersection_points[surf_idx][ray_idx]`, the value returned by the call;
  - `tracer.lighting_scene`, one `(scene, perturbed_scene)` entry per call, where `scene[surf_idx] = [incident_rays, reflected_rays]`;
  - `tracer.terminated_rays[surf_idx][ray_idx]`, which is `"no_intersection"`, `"out_of_boundary"` or `"behind_origin"` (see the hit rule below).
- **Slope error**: every reflection is also computed with a perturbed surface normal. The normal is tilted by Gaussian amounts along the surface's two tangent directions, so the effect is the same whatever the surface orientation.
  - Settings: `trace_new_scene(..., slope_error=(σx, σy), rng=seed)`. The default is `(0.001, 0.001)`, `None` turns the slope error off, and `rng` makes runs reproducible.
  - Propagation: in sequential mode, the perturbed rays are traced along the whole chain. Each surface's perturbed incident rays are the perturbed rays reflected by the previous surface, so slope errors add up down to the receiver.
  - Perturbed results: `lighting_scene[-1][1]`, `tracer.pertubed_intersection_points` and `tracer.pertubed_terminated_rays`. They are keyed by the same `ray_idx` as the nominal results.
  - `compute_slope_error_angular_deviations(scene, perturbed_scene)` returns `{surf_idx: {ray_idx: [dev_x, dev_y, dev_total]}}` in radians, measured in a frame tied to each nominal reflected ray. From the second surface onwards, these are the accumulated deviations.
- **Post-processing**: `plane_analysis("XY" | "XZ" | "YZ", position, rays)` intersects rays with an axis-aligned plane, and `geometry_analysis(equation, rays, hit_rule="nearest", boundaries=None)` intersects them with any surface f(x, y, z) = 0 (use `hit_rule="first"` to keep only crossings in front of each ray, e.g. for a receiver).

### Analysis — `optical_ray_tracer/analyses/optical/`

- `density_calculations.kde_3d_tree(points)` gives the 3D kernel density of hit points (scikit-learn `KernelDensity`). Use it, for example, to map the flux distribution around a focal point. `density[i, j, k]` is the density at `(X[i], Y[j], Z[k])`.
  - `weights={ray_idx: w}` gives each point its relative intensity w ∈ [0, 1], e.g. from the intensity profile of a large source.
  - The incident `ray_idx` is kept along the whole chain, so the weights of the incident rays can be passed as they are.

### Utilities — `optical_ray_tracer/utils/`

- `rotation_vect.rotationVectU(axis, angle)` returns a rotation matrix (Rodrigues' formula).
- `sphericalcartesian.sphericalcartesian([theta, phi])` converts a direction to a unit vector `[sinθcosφ, sinθsinφ, −cosθ]`, so θ = 0 points down.

---

## Installation

Requires Python ≥ 3.10.

From PyPI:

```bash
pip install optical-ray-collector
```

The distribution is named `optical-ray-collector`, but the package you import is `optical_ray_tracer`.

From source, for development:

```bash
git clone https://github.com/Damzo/optical_ray_collector.git
cd optical_ray_collector
pip install -e .            # or: pip install -r requirements.txt
```

Dependencies: `numpy`, `sympy`, `scipy`, `matplotlib`, `pandas`, `numba`, `scikit-learn`.

> **Upgrading from 1.4.x?** Version 2.0.0 changes two behaviours: rotation angles are now given in degrees, and `trace_new_scene()` results are keyed by surface first. See [CHANGELOG.md](https://github.com/Damzo/optical_ray_collector/blob/main/CHANGELOG.md) for the migration notes.

---

## Quick start

### Sequential scene: sun → parabolic dish

```python
from optical_ray_tracer.configurations.geometries.Parabolic import ParabolicReflector
from optical_ray_tracer.rays.source import point_source
from optical_ray_tracer.rays.raytracer.ray_tracer import Tracer

tracer = Tracer()

# 1. Geometry: paraboloid with focal length 1 m and height 2 m
dish = ParabolicReflector(f_x=1.0, f_y=1.0, h=2.0, surf_pos=[0, 0, 0])
surf_idx, _ = tracer.add_surface(str(dish.symbolic_equation()), dish.boundaries())

# 2. Source: distant point source, rays aimed at the dish aperture
sun = point_source.Source(position_x=0.0, position_y=0.0, position_z=1.5e8)
directions, origins = dish.generate_rays_from_source(16, sun)
tracer.add_rays(directions, origins)

# 3. Trace
intersections, reflected = tracer.trace_new_scene()
print(f"{len(intersections[surf_idx])} rays hit surface {surf_idx}")
print("Terminated rays:", tracer.terminated_rays[surf_idx])

# 4. Per-surface results
scene, perturbed_scene = tracer.lighting_scene[-1]
incident, reflected_on_surface = scene[surf_idx]   # {ray_idx: [direction, origin]}
```

### Analysis: focal plane and slope error

```python
from optical_ray_tracer.analyses.optical.density_calculations import kde_3d_tree

# Where do reflected rays cross the focal plane z = f = 1 m?
focal_hits = tracer.plane_analysis("XY", 1.0, reflected_on_surface)
density = kde_3d_tree(focal_hits, grid_size=32)    # density["density"] -> (32, 32, 32) array

# Angular deviation caused by the surface slope error
deviations = tracer.compute_slope_error_angular_deviations(scene, perturbed_scene)
```

### Parallel scene: two independently lit mirrors

```python
from optical_ray_tracer.configurations.geometries.Plane import RectangularPlaneReflector, CircularPlaneReflector

tracer = Tracer()
plane0 = RectangularPlaneReflector((2.0, 1.0), surf_pos=[0, 0, 0])
plane1 = CircularPlaneReflector((1.0,), surf_pos=[0, 0, 5])
tracer.add_surface(str(plane0.symbolic_equation()), plane0.boundaries())
tracer.add_surface(str(plane1.symbolic_equation()), plane1.boundaries())

# rays_dict={} keeps each ray set out of tracer.incident_rays
_, rays0 = tracer.add_rays(*plane0.generate_rays_from_source(9, point_source.Source(position_z=5.0)), rays_dict={})
_, rays1 = tracer.add_rays(*plane1.generate_rays_from_source(9, point_source.Source(position_z=15.0)), rays_dict={})

intersections, _ = tracer.trace_new_scene(incident_rays=[rays0, rays1], parallel_lighting=True)
```

### Fast tracing: `tracing="compiled"`

```python
tracer = Tracer(tracing="compiled")     # everything else as in the examples above
```

- **What it does differently:** it compiles each surface's intersection polynomial and normal once with `sympy.lambdify`, then traces all the rays of a surface at once with NumPy.
- **Speed:** 20,000 rays through a paraboloid → plane chain take about 0.09 s, where `"symbolic"` needs about 0.6 s for 200 rays. Compiling each surface takes a one-off ~0.1 s, cached per instance.
- **Accuracy:** hit points are exact to float64 precision, like `"symbolic"`.
- **Fallback:** surfaces that are polynomial in the ray parameter are compiled: paraboloids, planes and cylinders, plus surfaces whose square roots can be eliminated. For any other surface, such as a `GivenGeometry` containing `sin` or `exp`, it warns and falls back to the symbolic engine.
- **Slope error:** the draws are vectorised, so perturbed rays match `"symbolic"` only statistically.

---

## Conventions and limitations

- **Surface indices** must be the contiguous integers `0..N-1`, in insertion order, which is what `add_surface` produces. `trace_new_scene` checks this and raises `ValueError` otherwise.
- **Hit rule:** `trace_new_scene(..., hit_rule=...)` decides which intersection a ray P(t) = O + t·d keeps:
  - `"nearest"` (default): the point nearest the ray origin, in front of or behind it (min |t|).
  - `"first"`: the first point met along the propagation (min t with t > 0). Rays whose intersections all lie behind their origin are terminated as `"behind_origin"`. This is the physically causal choice. In the cylinder → plane test scene (100 rays), `"nearest"` counts 16 of the 42 plane hits from behind the ray.
- **Precision:** before solving, each ray's origin is moved along the ray close to the surface, and the symbolic engine evaluates its solutions at 50 digits. Hit points are exact to float64 precision even with a source 1.5e8 m away.
- **Placement and rotation:** every geometry is defined in its own local frame. A local point X is placed in the world at **x = p + R·X**, where p is `surf_pos` and R is the rotation, so the world equation is F(Rᵀ·(x − p)) = 0. The boundary box, the aperture used to aim rays, and the normals all follow the same placement.
  - `rotation_angle` is given in **degrees** and converted to radians internally (`geometry.rotation_angle`; the input value is kept in `rotation_angle_deg`).
  - The rotation axis is `orientation`. The defaults are x for `ParabolicReflector` and `GivenGeometry`, and y for planes.
  - For `CylindricalReflector`, `orientation` is the direction of the cylinder's axis, and `rotation_angle` rolls the cylinder about that axis. Its cross-section is the ellipse (X/a)² + (Z/b)² = 1, with a = thickness/2 and b = height.
- **Boundaries** are axis-aligned boxes `[[xmin, xmax], [ymin, ymax], [zmin, zmax]]`. An intersection outside the box is discarded (`"out_of_boundary"`).
- **Rays with a zero z-component:** both engines and `geometry_analysis` parametrise rays as `O + t·d` and support them.
- **Surfaces of degree 4 and more** (e.g. a torus): the symbolic engine solves them ray by ray numerically (50 digits) instead of building the huge closed-form solutions.
- **Symbolic engine speed:** it solves each surface's intersection once, symbolically, with the ray's origin and direction as symbols. It then evaluates the solution for each ray at 50 significant digits, which takes about 2–3 ms per ray. The one-off solve takes about 0.2–0.4 s per surface and is cached for all instances. Use `tracing="compiled"` for large ray counts (10⁴ and more).

---

## Project structure

```
optical_ray_tracer/
├── configurations/
│   ├── main.py                # Geometry base class
│   └── geometries/            # Parabolic, Cylindric, Plane, given_geometry, ring_array
├── rays/
│   ├── source/                # RaySource base class, point_source, large_source
│   └── raytracer/
│       ├── ray_tracer.py             # Tracer: single entry point, tracing="symbolic" | "compiled"
│       ├── uncompiled_ray_tracer.py  # UncompiledTracer: fully symbolic engine
│       └── compiled_ray_tracer.py    # CompiledTracer: compiled engine (lambdify + NumPy)
├── analyses/
│   ├── optical/               # density_calculations (3D KDE)
│   ├── thermal/               # (placeholder)
│   └── thermodynamical/       # (placeholder)
├── utils/                     # rotation matrix, spherical → Cartesian
└── tests/                     # pytest suite, scene harness, plotting scripts
```

---

## Tests and visualisation

```bash
pytest optical_ray_tracer/tests
```

- `conftest.py` forces matplotlib's non-interactive `Agg` backend, so the suite runs headless.
- `scene_harness.py` builds multi-surface scenes for either lighting mode from any combination of geometries and sources. `plot_full_scene.py` uses it to draw 3D scenes into `tests/plot_output/`:

| Sequential lighting | Parallel lighting |
|---|---|
| ![Sequential scene](https://raw.githubusercontent.com/Damzo/optical_ray_collector/main/optical_ray_tracer/tests/plot_output/sequencing_scene.png) | ![Parallel scene](https://raw.githubusercontent.com/Damzo/optical_ray_collector/main/optical_ray_tracer/tests/plot_output/parallel_scene.png) |

- `test_parabolique.py` is a manual demo script, not a pytest test.
- `tests/parabole_optimisation/` is a separate study (SLSQP optimisation of a series of parabolas). It has its own `README_PARABOLE.txt`.

---

## Roadmap

- Thermal and thermodynamic analyses (`analyses/thermal`, `analyses/thermodynamical`)
- Weather and solar-irradiance data input
- Web visualisation of traced scenes (API and 2D/3D frontend)
- Tracing `RingarrayReflector` as a set of tracer surfaces
- Configurable slope-error σ in `trace_new_scene`

---

## Authors

Dam-Bè L. DOUTI, Henoc N'GASAMA, Serge DZO

## Contributing

Contributions are welcome:

1. Fork the repository and create a branch from `dev`.
2. Add or update tests under `optical_ray_tracer/tests/` and make sure `pytest` passes.
3. Open a pull request.

## License

Released under the [GNU General Public License v3.0](https://github.com/Damzo/optical_ray_collector/blob/main/LICENSE).

## Changelog

Release history and migration notes: [CHANGELOG.md](https://github.com/Damzo/optical_ray_collector/blob/main/CHANGELOG.md).
