optiland-sms 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,59 @@
1
+ """
2
+ Python-specific module: optiland_sms package
3
+ Copyright 2026 ray-tracing-shapely authors and contributors
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+
17
+ Python translation Copyright 2026 ray-tracing-shapely authors and contributors
18
+
19
+ Licensed under the Apache License, Version 2.0 (the "License");
20
+ you may not use this file except in compliance with the License.
21
+ You may obtain a copy of the License at
22
+
23
+ http://www.apache.org/licenses/LICENSE-2.0
24
+
25
+ ===============================================================================
26
+ optiland_sms
27
+ ===============================================================================
28
+ Registers ray_tracing_shapely's SMS (Minano-Benitez Simultaneous Multiple
29
+ Surface) lens surfaces with Optiland's sequential engine, as the surface type
30
+ "sms_spline", through Optiland's ``optiland.surfaces`` entry point: no import
31
+ of this package and no edit to Optiland is needed.
32
+
33
+ The input is a ``profile.json``: one spline span of a revolve profile becomes
34
+ a surface of revolution whose meridian is the profile's own curve
35
+ (``geometry.SMSSplineGeometry``). Under Optiland's torch backend a trace
36
+ through it is differentiable with respect to the spline's points.
37
+
38
+ What it is for: refraction-only lenses (an RR) in the sequential engine. A
39
+ mirror or a total internal reflection does not fit a sequential trace, and
40
+ Optiland's non-sequential engine has no plugin hook: those designs reach 3D
41
+ through the ray_tracing_shapely_optiland scene bridge instead.
42
+
43
+ Modules:
44
+ - meridian: one spline span, read and checked, in a surface's (r, z) frame.
45
+ - geometry: the surface, an Optiland NewtonRaphsonGeometry.
46
+ - register: the entry point.
47
+
48
+ Named for Optiland's audience (entry-point discovery is a channel into
49
+ Optiland's own users). See dev_doc/architecture/components/optiland_sms_plugin.md.
50
+ ===============================================================================
51
+ """
52
+
53
+ from .geometry import SMSSplineGeometry
54
+ from .meridian import Meridian, read_meridian
55
+ from .register import SURFACE_TYPE, register
56
+
57
+ __version__ = "0.1.1"
58
+
59
+ __all__ = ["SMSSplineGeometry", "Meridian", "read_meridian", "register", "SURFACE_TYPE", "__version__"]
@@ -0,0 +1,250 @@
1
+ """
2
+ Python-specific module: geometry
3
+ Copyright 2026 ray-tracing-shapely authors and contributors
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+
17
+ ===============================================================================
18
+ GEOMETRY -- a spline meridian as an Optiland sequential surface
19
+ ===============================================================================
20
+ ``SMSSplineGeometry`` is a surface of revolution about the local z axis whose
21
+ meridian is a profile's spline span (``meridian.read_meridian``). It is an
22
+ Optiland ``NewtonRaphsonGeometry``: it gives the sag and the normal, and
23
+ Optiland's own solve finds where a ray meets it. Under the torch backend that
24
+ solve gives first-order gradients through the converged intersection (its
25
+ one-step implicit correction).
26
+
27
+ The sag is the profile's own curve, not a second curve through its points.
28
+ At a radius r:
29
+
30
+ 1. the piece of the meridian whose radius range holds r is found;
31
+ 2. the piece's parameter u where r(u) = r is found by Newton's method from a
32
+ linear guess, detached from the gradient; the radius is strictly monotonic
33
+ on every piece (the reader checks it), so the root is unique;
34
+ 3. one more Newton step, attached, makes u's derivative the exact first-order
35
+ one (the implicit function theorem), with respect to r and to the points;
36
+ 4. the sag is z(u).
37
+
38
+ The normal comes from the meridian's tangent at u: dz/dr = z'(u) / r'(u).
39
+ Beyond the rim the sag goes on along the rim's tangent, so a Newton iterate
40
+ that strays past the rim sees a smooth surface; the aperture limits the rays.
41
+
42
+ The spline's points are held as a backend array (``self.points``): under
43
+ torch it can be a leaf that requires a gradient, and a trace is then
44
+ differentiable with respect to the points. The tangents stay fixed.
45
+ ===============================================================================
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ from typing import Any, Dict
51
+
52
+ import numpy as np
53
+ import optiland.backend as be
54
+ from optiland.coordinate_system import CoordinateSystem
55
+ from optiland.geometries.newton_raphson import NewtonRaphsonGeometry
56
+
57
+ from .meridian import Meridian, ProfileLike, hermite_point, load_profile, read_meridian
58
+
59
+ # Newton steps on r(u) = r before the attached one. The guess is linear on a
60
+ # piece of a cubic, and the convergence quadratic: six reach rounding.
61
+ DETACHED_STEPS = 6
62
+
63
+
64
+ def _detach(x):
65
+ return x.detach() if hasattr(x, "detach") else x
66
+
67
+
68
+ class SMSSplineGeometry(NewtonRaphsonGeometry):
69
+ """A surface of revolution whose meridian is a profile.json spline span.
70
+
71
+ Args:
72
+ coordinate_system: The surface's coordinate system; its vertex is
73
+ where the span meets the axis.
74
+ profile: The profile, as a dict or the path of its JSON file.
75
+ span: The span's short label.
76
+ reverse: Whether light travels against the profile's axis direction,
77
+ so local +z runs against it.
78
+ tol: Tolerance of Optiland's intersection solve.
79
+ max_iter: Iteration limit of that solve.
80
+
81
+ Attributes:
82
+ meridian: The span as read (``meridian.Meridian``).
83
+ points: The spline's points (n, 2) as (r, z), a backend array.
84
+ tangents: The unit tangents (n, 2), a backend array.
85
+ rim_radius: The radius of the span's end away from the axis.
86
+ """
87
+
88
+ def __init__(
89
+ self,
90
+ coordinate_system: CoordinateSystem,
91
+ profile: ProfileLike,
92
+ span: str,
93
+ reverse: bool = False,
94
+ tol: float = 1e-10,
95
+ max_iter: int = 100,
96
+ ) -> None:
97
+ self.profile = load_profile(profile)
98
+ self.span = span
99
+ self.reverse = bool(reverse)
100
+ self.meridian: Meridian = read_meridian(self.profile, span, reverse=self.reverse)
101
+ self.points = be.array(np.array(self.meridian.points, dtype=float))
102
+ self.tangents = be.array(np.array(self.meridian.tangents, dtype=float))
103
+ pieces = self.meridian.pieces
104
+ self._k = np.array([q.k for q in pieces], dtype=np.int64)
105
+ self._u_from = np.array([q.u_from for q in pieces], dtype=float)
106
+ self._u_to = np.array([q.u_to for q in pieces], dtype=float)
107
+ self.rim_radius = float(self.meridian.rim_radius)
108
+ super().__init__(coordinate_system, self._seed_radius(), 0.0, tol, max_iter)
109
+ self.is_symmetric = True
110
+
111
+ def __str__(self) -> str:
112
+ return "SMS Spline"
113
+
114
+ # --- the meridian, on the backend ------------------------------------------
115
+
116
+ def _coefficients(self):
117
+ """Each piece's cubic in r and in z: four (pieces,) arrays each."""
118
+ p, t = self.points, self.tangents
119
+ k = self._k
120
+ p0, p1 = p[k], p[k + 1]
121
+ h = be.sqrt(be.sum((p1 - p0) ** 2, axis=1))
122
+ m0, m1 = t[k] * h[:, None], t[k + 1] * h[:, None]
123
+ a = p0
124
+ b = m0
125
+ c = -3 * p0 - 2 * m0 + 3 * p1 - m1
126
+ d = 2 * p0 + m0 - 2 * p1 + m1
127
+ return (a[:, 0], b[:, 0], c[:, 0], d[:, 0]), (a[:, 1], b[:, 1], c[:, 1], d[:, 1])
128
+
129
+ @staticmethod
130
+ def _cubic(co, u):
131
+ a, b, c, d = co
132
+ return a + u * (b + u * (c + u * d))
133
+
134
+ @staticmethod
135
+ def _cubic_d(co, u):
136
+ _, b, c, d = co
137
+ return b + u * (2 * c + 3 * u * d)
138
+
139
+ def _knots(self, cr):
140
+ """The radius at each piece's two ends, detached: (pieces,) arrays."""
141
+ u_from, u_to = be.array(self._u_from), be.array(self._u_to)
142
+ cr_d = tuple(_detach(x) for x in cr)
143
+ return self._cubic(cr_d, u_from), self._cubic(cr_d, u_to)
144
+
145
+ def _solve(self, r):
146
+ """For each radius: the piece, the cubic's coefficients there, and u."""
147
+ cr, cz = self._coefficients()
148
+ r_from, r_to = self._knots(cr)
149
+ r_d = _detach(r)
150
+ n = len(self._k)
151
+ idx = be.searchsorted(r_to, r_d)
152
+ idx = be.clip(idx, 0, n - 1)
153
+ u_from, u_to = be.array(self._u_from)[idx], be.array(self._u_to)[idx]
154
+ ra, rb = r_from[idx], r_to[idx]
155
+ crs = tuple(x[idx] for x in cr)
156
+ czs = tuple(x[idx] for x in cz)
157
+ crs_d = tuple(_detach(x) for x in crs)
158
+ # The radius inside the piece (beyond the rim, the rim: the sag is
159
+ # extended along the rim's tangent below).
160
+ r_in = be.clip(r_d, 0.0, self.rim_radius)
161
+ frac = (r_in - ra) / (rb - ra)
162
+ u = u_from + frac * (u_to - u_from)
163
+ lo, hi = be.minimum(u_from, u_to), be.maximum(u_from, u_to)
164
+ for _ in range(DETACHED_STEPS):
165
+ u = u - (self._cubic(crs_d, u) - r_in) / self._cubic_d(crs_d, u)
166
+ u = be.minimum(be.maximum(u, lo), hi)
167
+ u = _detach(u)
168
+ # The attached step: u's first derivative is the implicit one.
169
+ r_att = be.where(r_d > self.rim_radius, be.zeros_like(r) + self.rim_radius, r)
170
+ u = u - (self._cubic(crs, u) - r_att) / self._cubic_d(crs, u)
171
+ return crs, czs, u
172
+
173
+ def _radius(self, x, y):
174
+ # A tiny floor keeps the derivative of the radius finite on the axis,
175
+ # where the meridian is flat and the sag's derivative is zero anyway.
176
+ return be.sqrt(x**2 + y**2 + 1e-300)
177
+
178
+ def _sag_and_slope(self, x, y):
179
+ x, y = be.array(x), be.array(y)
180
+ r = self._radius(x, y)
181
+ shape = r.shape
182
+ r = be.ravel(r)
183
+ crs, czs, u = self._solve(r)
184
+ z = self._cubic(czs, u)
185
+ slope = self._cubic_d(czs, u) / self._cubic_d(crs, u)
186
+ beyond = r > self.rim_radius
187
+ z = be.where(beyond, z + slope * (r - self.rim_radius), z)
188
+ return be.reshape(z, shape), be.reshape(slope, shape), be.reshape(r, shape)
189
+
190
+ # --- NewtonRaphsonGeometry --------------------------------------------------
191
+
192
+ def sag(self, x=0, y=0):
193
+ """The sag at (x, y): the meridian's z at the radius hypot(x, y).
194
+
195
+ Args:
196
+ x: The x-coordinate(s).
197
+ y: The y-coordinate(s).
198
+
199
+ Returns:
200
+ The sag, the shape of x and y.
201
+ """
202
+ return self._sag_and_slope(x, y)[0]
203
+
204
+ def _surface_normal(self, x, y):
205
+ """The unit normal (nx, ny, nz) at (x, y), with nz < 0 (Optiland's convention)."""
206
+ _, slope, r = self._sag_and_slope(x, y)
207
+ x, y = be.array(x), be.array(y)
208
+ dfdx, dfdy = slope * x / r, slope * y / r
209
+ mag = be.sqrt(dfdx**2 + dfdy**2 + 1)
210
+ return dfdx / mag, dfdy / mag, -1 / mag
211
+
212
+ def _seed_radius(self) -> float:
213
+ """The radius of Optiland's seed sphere: the sphere through the vertex and the rim.
214
+
215
+ Optiland starts its intersection solve where a ray meets the base
216
+ sphere. A ray the sphere does not reach has no start, and some
217
+ Optiland releases leave it non-finite. The sphere through the vertex
218
+ and the rim point reaches the whole aperture (its radius is at least
219
+ the rim's), which the vertex's own radius of curvature need not: the
220
+ RR's front face curves more at its vertex than its rim radius allows.
221
+ Infinite (a plane) for a flat meridian.
222
+ """
223
+ last = self.meridian.pieces[-1]
224
+ r, z = hermite_point(self.meridian.points, self.meridian.tangents, last.k, last.u_to)
225
+ if abs(z) < 1e-12 * max(r, 1e-300):
226
+ return float("inf")
227
+ return (r * r + z * z) / (2.0 * z)
228
+
229
+ # --- Optiland's other hooks -------------------------------------------------
230
+
231
+ def flip(self) -> None:
232
+ """Turn the surface round: light now travels the other way along the axis."""
233
+ self.__init__(self.cs, self.profile, self.span, not self.reverse, self.tol, self.max_iter)
234
+
235
+ def scale(self, scale_factor: float) -> None:
236
+ """Not supported: a profile's coordinates are its design's."""
237
+ raise NotImplementedError("an SMS spline surface is not scaled; scale the profile instead.")
238
+
239
+ def to_dict(self) -> Dict[str, Any]:
240
+ data = super().to_dict()
241
+ data.update({"profile": self.profile, "span": self.span, "reverse": self.reverse})
242
+ return data
243
+
244
+ @classmethod
245
+ def from_dict(cls, data: Dict[str, Any]) -> "SMSSplineGeometry":
246
+ missing = {"cs", "profile", "span"} - data.keys()
247
+ if missing:
248
+ raise ValueError(f"Missing required keys: {missing}")
249
+ return cls(CoordinateSystem.from_dict(data["cs"]), data["profile"], data["span"],
250
+ data.get("reverse", False), data.get("tol", 1e-10), data.get("max_iter", 100))
@@ -0,0 +1,280 @@
1
+ """
2
+ Python-specific module: meridian
3
+ Copyright 2026 ray-tracing-shapely authors and contributors
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+
17
+ ===============================================================================
18
+ MERIDIAN -- one spline span of a profile.json, in a surface's own frame
19
+ ===============================================================================
20
+ A ``profile.json`` describes a 2D outline: points, exact outward normals, and
21
+ spans, each span one physical surface. A spline span is a cubic Hermite curve
22
+ through ``points`` with unit ``tangents``, each segment's tangents scaled by
23
+ its chord, over the parameter range ``domain`` (the segment index plus the
24
+ fraction along it). A revolve profile declares the axis it turns about.
25
+
26
+ ``read_meridian`` takes one spline span and returns it in the frame of a
27
+ sequential surface of revolution:
28
+
29
+ - r: the distance from the revolve axis, on the side the half-section lies
30
+ (the left of the axis direction);
31
+ - z: along the axis, from the span's vertex (where it meets the axis). With
32
+ ``reverse`` it runs against the profile's axis direction, for light that
33
+ travels that way.
34
+
35
+ The map is a rotation (and, with ``reverse``, a reflection), so the curve in
36
+ (r, z) is the same Hermite curve: its points and tangents are mapped, and its
37
+ chords are unchanged.
38
+
39
+ A surface is one span (one curve from the axis to its rim). The reader
40
+ refuses, with a ValueError that says why:
41
+
42
+ - a profile whose schema it does not know, or that is not a revolve;
43
+ - a label that names no span, or more than one;
44
+ - a span that is not a spline;
45
+ - a span with neither end on the axis (an annular zone: a surface made of
46
+ more than one span);
47
+ - a span whose radius is not strictly monotonic along it, so that it is not
48
+ single-valued as z(r).
49
+ ===============================================================================
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import json
55
+ import math
56
+ from dataclasses import dataclass
57
+ from pathlib import Path
58
+ from typing import Any, Dict, List, Sequence, Tuple, Union
59
+
60
+ # Spline spans exist from schema 1.2. Later versions add fields this reader
61
+ # does not use (sources, rayfiles, aspheres, fit records).
62
+ KNOWN_SCHEMAS = ("1.2", "1.3", "1.4", "1.5")
63
+
64
+ # How close to the axis a span's end must be, relative to the span's size.
65
+ AXIS_TOL = 1e-9
66
+
67
+ XY = Tuple[float, float]
68
+ ProfileLike = Union[Dict[str, Any], str, Path]
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class Piece:
73
+ """One cubic segment of the meridian, or the part of it inside the domain.
74
+
75
+ Attributes:
76
+ k: The spline segment's index (points k and k + 1).
77
+ u_from: Where along the segment the piece starts, in [0, 1]: the end
78
+ nearer the axis.
79
+ u_to: Where it ends: the end nearer the rim.
80
+ """
81
+
82
+ k: int
83
+ u_from: float
84
+ u_to: float
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class Meridian:
89
+ """A spline span in a surface's (r, z) frame.
90
+
91
+ Attributes:
92
+ points: The spline's points (r, z), all of them, z from the vertex.
93
+ tangents: The unit tangents at the points, in the same frame.
94
+ pieces: The parts of segments the domain covers, from the axis to
95
+ the rim.
96
+ samples: The profile's own samples of the span (r, z).
97
+ normals: The profile's exact unit normals at the samples, in (r, z).
98
+ label: The span's short label.
99
+ reverse: Whether z runs against the profile's axis direction.
100
+ vertex: The vertex (where the span meets the axis), in the profile's
101
+ coordinates.
102
+ vertex_along_axis: The vertex's distance from the axis point along
103
+ the profile's axis direction (whatever ``reverse``). Two faces'
104
+ values give the thickness between them: the vertex is the curve's,
105
+ which lies between its points, not one of them.
106
+ """
107
+
108
+ points: Tuple[XY, ...]
109
+ tangents: Tuple[XY, ...]
110
+ pieces: Tuple[Piece, ...]
111
+ samples: Tuple[XY, ...]
112
+ normals: Tuple[XY, ...]
113
+ label: str
114
+ reverse: bool
115
+ vertex: XY
116
+ vertex_along_axis: float
117
+
118
+ @property
119
+ def rim_radius(self) -> float:
120
+ """The radius of the span's end away from the axis."""
121
+ last = self.pieces[-1]
122
+ return hermite_point(self.points, self.tangents, last.k, last.u_to)[0]
123
+
124
+
125
+ def load_profile(profile: ProfileLike) -> Dict[str, Any]:
126
+ """A profile as a dict: given as one, or read from a JSON file."""
127
+ if isinstance(profile, dict):
128
+ return profile
129
+ with open(profile, encoding="utf-8") as fh:
130
+ return json.load(fh)
131
+
132
+
133
+ def hermite_coefficients(points: Sequence[XY], tangents: Sequence[XY], k: int):
134
+ """Segment k's cubic as (a, b, c, d) per coordinate: a + b u + c u^2 + d u^3.
135
+
136
+ The same coefficients as the profile's writer: the tangents scaled by the
137
+ chord between points k and k + 1.
138
+ """
139
+ p0, p1 = points[k], points[k + 1]
140
+ h = math.dist(p0, p1)
141
+ m0 = (tangents[k][0] * h, tangents[k][1] * h)
142
+ m1 = (tangents[k + 1][0] * h, tangents[k + 1][1] * h)
143
+ return tuple(
144
+ (p0[i], m0[i], -3 * p0[i] - 2 * m0[i] + 3 * p1[i] - m1[i], 2 * p0[i] + m0[i] - 2 * p1[i] + m1[i])
145
+ for i in (0, 1)
146
+ )
147
+
148
+
149
+ def hermite_point(points: Sequence[XY], tangents: Sequence[XY], k: int, u: float) -> XY:
150
+ """The point at fraction u of segment k."""
151
+ out = []
152
+ for a, b, c, d in hermite_coefficients(points, tangents, k):
153
+ out.append(a + u * (b + u * (c + u * d)))
154
+ return out[0], out[1]
155
+
156
+
157
+ def _span(profile: Dict[str, Any], label: str) -> Dict[str, Any]:
158
+ found = [s for s in profile.get("spans", []) if s.get("short_label") == label]
159
+ if len(found) != 1:
160
+ labels = [s.get("short_label") for s in profile.get("spans", [])]
161
+ raise ValueError(f"the profile has {len(found)} spans labelled {label!r}, not one; "
162
+ f"its labels are {labels}.")
163
+ return found[0]
164
+
165
+
166
+ def _frame(profile: Dict[str, Any]) -> Tuple[XY, XY, XY]:
167
+ symmetry = profile.get("symmetry") or {}
168
+ if symmetry.get("kind") != "revolve":
169
+ raise ValueError(f"not a revolve profile: symmetry kind is {symmetry.get('kind')!r}.")
170
+ if symmetry.get("azimuth_deg") is not None:
171
+ raise ValueError("a revolve over part of a turn (azimuth_deg) is not a sequential surface.")
172
+ axis = symmetry.get("axis") or {}
173
+ try:
174
+ point = (float(axis["point"][0]), float(axis["point"][1]))
175
+ ux, uy = float(axis["direction"][0]), float(axis["direction"][1])
176
+ except (TypeError, KeyError, IndexError, ValueError):
177
+ raise ValueError(f"symmetry needs axis = {{'point': [a, b], 'direction': [ux, uy]}}, "
178
+ f"got {axis!r}.") from None
179
+ length = math.hypot(ux, uy)
180
+ if length == 0.0:
181
+ raise ValueError("the revolve axis direction is zero.")
182
+ ux, uy = ux / length, uy / length
183
+ return point, (ux, uy), (-uy, ux)
184
+
185
+
186
+ def _monotonic(points, tangents, piece: Piece) -> float:
187
+ """The smallest of dr/du times its sign along a piece; > 0 if r is strictly monotonic."""
188
+ (_, b, c, d), _ = hermite_coefficients(points, tangents, piece.k)
189
+ lo, hi = sorted((piece.u_from, piece.u_to))
190
+ us = [lo, hi]
191
+ if d != 0.0:
192
+ u_star = -c / (3.0 * d) # the extremum of the quadratic dr/du
193
+ if lo < u_star < hi:
194
+ us.append(u_star)
195
+ sign = 1.0 if piece.u_to > piece.u_from else -1.0
196
+ return min(sign * (b + u * (2 * c + 3 * u * d)) for u in us)
197
+
198
+
199
+ def read_meridian(profile: ProfileLike, label: str, *, reverse: bool = False) -> Meridian:
200
+ """One spline span of a revolve profile, in a sequential surface's (r, z) frame.
201
+
202
+ Args:
203
+ profile: The profile, as a dict or the path of its JSON file.
204
+ label: The span's ``short_label``.
205
+ reverse: z against the profile's axis direction (light travelling that way).
206
+
207
+ Returns:
208
+ The Meridian, its z measured from the vertex.
209
+
210
+ Raises:
211
+ ValueError: For anything the module docstring lists.
212
+ """
213
+ profile = load_profile(profile)
214
+ version = str(profile.get("schema_version"))
215
+ if version not in KNOWN_SCHEMAS:
216
+ raise ValueError(f"profile schema {version!r} is not one this reader knows {KNOWN_SCHEMAS}.")
217
+ point, direction, left = _frame(profile)
218
+ span = _span(profile, label)
219
+ curve = span.get("curve") or {}
220
+ if curve.get("type") != "spline":
221
+ raise ValueError(f"span {label!r} is a {curve.get('type')!r}, not a spline.")
222
+ sign = -1.0 if reverse else 1.0
223
+
224
+ def to_rz(p) -> XY:
225
+ dx, dy = float(p[0]) - point[0], float(p[1]) - point[1]
226
+ return dx * left[0] + dy * left[1], sign * (dx * direction[0] + dy * direction[1])
227
+
228
+ def vec_to_rz(v) -> XY:
229
+ x, y = float(v[0]), float(v[1])
230
+ return x * left[0] + y * left[1], sign * (x * direction[0] + y * direction[1])
231
+
232
+ points = [to_rz(p) for p in curve["points"]]
233
+ tangents = []
234
+ for t in curve["tangents"]:
235
+ tr, tz = vec_to_rz(t)
236
+ n = math.hypot(tr, tz)
237
+ if n == 0.0 or not math.isfinite(n):
238
+ raise ValueError(f"span {label!r} has a zero or non-finite tangent.")
239
+ tangents.append((tr / n, tz / n))
240
+ if len(points) < 2 or len(points) != len(tangents):
241
+ raise ValueError(f"span {label!r} needs at least 2 points and one tangent per point.")
242
+ last = len(points) - 1
243
+ p0, p1 = (float(v) for v in curve.get("domain", (0.0, last)))
244
+ if not 0.0 <= min(p0, p1) <= max(p0, p1) <= last or p0 == p1:
245
+ raise ValueError(f"span {label!r} has a domain {[p0, p1]} outside [0, {last}].")
246
+
247
+ def at(p: float) -> XY:
248
+ k = min(int(math.floor(p)), last - 1)
249
+ return hermite_point(points, tangents, k, p - k)
250
+
251
+ size = max(math.dist(points[0], points[-1]), max(abs(c) for q in points for c in q), 1e-300)
252
+ r0, r1 = at(p0)[0], at(p1)[0]
253
+ if abs(r0) <= AXIS_TOL * size:
254
+ start, end = p0, p1
255
+ elif abs(r1) <= AXIS_TOL * size:
256
+ start, end = p1, p0
257
+ else:
258
+ raise ValueError(f"span {label!r} does not meet the axis (r = {r0:.6g} and {r1:.6g} at its ends): "
259
+ "a surface made of more than one span is not supported.")
260
+ # The pieces in increasing parameter, then ordered from the axis to the rim.
261
+ lo, hi = min(start, end), max(start, end)
262
+ pieces: List[Piece] = []
263
+ for k in range(min(int(math.floor(lo)), last - 1), last):
264
+ u_a, u_b = max(lo - k, 0.0), min(hi - k, 1.0)
265
+ if u_b - u_a > 1e-15:
266
+ pieces.append(Piece(k, u_a, u_b))
267
+ if start > end:
268
+ pieces = [Piece(q.k, q.u_to, q.u_from) for q in reversed(pieces)]
269
+ for piece in pieces:
270
+ if _monotonic(points, tangents, piece) <= 0.0:
271
+ raise ValueError(f"span {label!r}: the radius is not strictly monotonic on segment "
272
+ f"{piece.k}, so the surface is not single-valued as z(r).")
273
+ z_vertex = at(start)[1]
274
+ vertex = (point[0] + sign * z_vertex * direction[0], point[1] + sign * z_vertex * direction[1])
275
+ points = [(r, z - z_vertex) for r, z in points]
276
+ k0, k1 = int(span["index_start"]), int(span["index_end"])
277
+ samples = tuple((r, z - z_vertex) for r, z in (to_rz(q) for q in profile["points"][k0:k1]))
278
+ normals = tuple(vec_to_rz(v) for v in profile["normals"][k0:k1])
279
+ return Meridian(tuple(points), tuple(tangents), tuple(pieces), samples, normals, label, reverse,
280
+ vertex, sign * z_vertex)
@@ -0,0 +1,78 @@
1
+ """
2
+ Python-specific module: register
3
+ Copyright 2026 ray-tracing-shapely authors and contributors
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+
17
+ ===============================================================================
18
+ REGISTER -- the entry point Optiland's plugin loader calls
19
+ ===============================================================================
20
+ ``register()`` adds the surface type ``"sms_spline"`` to Optiland's
21
+ ``GeometryFactory``. The package declares it under the ``optiland.surfaces``
22
+ entry-point group, so Optiland calls it the first time it meets a surface
23
+ type it does not know; nothing has to import this package first.
24
+
25
+ A surface is then added as any other::
26
+
27
+ optic.surfaces.add(index=1, surface_type="sms_spline", profile="lens.profile.json",
28
+ span="N", reverse=True, thickness=0.8, material=...)
29
+
30
+ ``profile`` is the profile (a dict, or the path of its JSON file), ``span``
31
+ the spline span's short label, ``reverse`` whether light travels against the
32
+ profile's axis direction.
33
+ ===============================================================================
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ from dataclasses import dataclass
39
+ from typing import Any, Dict, Union
40
+
41
+ SURFACE_TYPE = "sms_spline"
42
+
43
+
44
+ @dataclass
45
+ class SMSSplineConfig:
46
+ """The arguments ``surface_type="sms_spline"`` accepts.
47
+
48
+ Attributes:
49
+ profile: The profile, as a dict or the path of its JSON file.
50
+ span: The spline span's short label.
51
+ reverse: Light travels against the profile's axis direction.
52
+ tol: Tolerance of Optiland's intersection solve.
53
+ max_iter: Iteration limit of that solve.
54
+ """
55
+
56
+ profile: Union[Dict[str, Any], str, None] = None
57
+ span: str = ""
58
+ reverse: bool = False
59
+ tol: float = 1e-10
60
+ max_iter: int = 100
61
+
62
+
63
+ def _create(cs: Any, config: SMSSplineConfig):
64
+ from .geometry import SMSSplineGeometry # noqa: PLC0415
65
+
66
+ if config.profile is None or not config.span:
67
+ raise ValueError('surface_type="sms_spline" needs profile= and span=.')
68
+ return SMSSplineGeometry(cs, config.profile, config.span, config.reverse, config.tol, config.max_iter)
69
+
70
+
71
+ def register() -> None:
72
+ """Register ``"sms_spline"`` with Optiland's GeometryFactory; calling it again does nothing."""
73
+ from optiland.surfaces.factories.geometry_factory import GeometryFactory # noqa: PLC0415
74
+ from optiland.surfaces.factories.geometry_factory import geometry_mapper # noqa: PLC0415
75
+
76
+ if SURFACE_TYPE in geometry_mapper:
77
+ return
78
+ GeometryFactory.register(SURFACE_TYPE, _create, SMSSplineConfig)
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.4
2
+ Name: optiland-sms
3
+ Version: 0.1.1
4
+ Summary: Miñano-Benítez SMS nonimaging profiles as an Optiland entry-point surface-geometry plugin
5
+ Author: ray-tracing-shapely authors and contributors
6
+ Author-email: Michele Benetti <michele@tiberavon.com>
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/tiberavon/optiland-sms
9
+ Project-URL: Repository, https://github.com/tiberavon/optiland-sms
10
+ Keywords: optiland,ray-tracing,optics,sms,nonimaging
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Scientific/Engineering :: Physics
19
+ Requires-Python: >=3.11
20
+ Description-Content-Type: text/markdown
21
+ License-File: NOTICE.txt
22
+ Requires-Dist: optiland>=0.6.3
23
+ Provides-Extra: torch
24
+ Requires-Dist: torch; extra == "torch"
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
27
+ Requires-Dist: torch; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # optiland-sms
31
+
32
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24416270.svg)](https://doi.org/10.5281/zenodo.24416270)
33
+
34
+ Miñano–Benítez SMS (Simultaneous Multiple Surface) lens surfaces in
35
+ [Optiland](https://github.com/optiland/optiland)'s sequential engine: a spline span of a
36
+ [`ray_tracing_shapely`](https://github.com/tiberavon/ray-tracing-shapely) `profile.json` becomes a
37
+ surface of revolution, traced exactly and, under Optiland's torch backend, differentiable with
38
+ respect to the spline's points.
39
+
40
+ The surface type `sms_spline` is registered through Optiland's `optiland.surfaces` entry point:
41
+ once the package is installed, Optiland finds it without an import and without any change to
42
+ Optiland.
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ pip install optiland-sms # numpy only
48
+ pip install "optiland-sms[torch]" # with torch, for gradients
49
+ ```
50
+
51
+ It needs Optiland 0.6.3 or later. It does not need `ray_tracing_shapely`: it reads that project's
52
+ profile files.
53
+
54
+ ## Use
55
+
56
+ ```python
57
+ from optiland.optic import Optic
58
+ from optiland.materials import IdealMaterial
59
+ from optiland.physical_apertures import RadialAperture
60
+ from optiland_sms import read_meridian
61
+
62
+ profile = "lens.profile.json" # a revolve profile whose faces are spline spans
63
+ front = read_meridian(profile, "N", reverse=True)
64
+ back = read_meridian(profile, "X", reverse=True)
65
+
66
+ op = Optic()
67
+ op.surfaces.add(index=0, thickness=10.0)
68
+ op.surfaces.add(index=1, surface_type="sms_spline", profile=profile, span="N", reverse=True,
69
+ thickness=front.vertex_along_axis - back.vertex_along_axis,
70
+ material=IdealMaterial(n=1.5), is_stop=True,
71
+ aperture=RadialAperture(front.rim_radius))
72
+ op.surfaces.add(index=2, surface_type="sms_spline", profile=profile, span="X", reverse=True,
73
+ thickness=5.0, aperture=RadialAperture(back.rim_radius))
74
+ op.surfaces.add(index=3)
75
+ ```
76
+
77
+ - `span` is the span's short label; `reverse` says that light travels against the profile's axis
78
+ direction.
79
+ - Take thicknesses from `vertex_along_axis`: a spline's vertex is where the curve meets the axis,
80
+ between its points, not one of them.
81
+ - Set each aperture to the surface's `rim_radius`. Beyond the rim the surface continues along the
82
+ rim's tangent, only so that the intersection solve sees a smooth surface.
83
+
84
+ For gradients, select the torch backend in float64 and make a surface's `points` a leaf:
85
+
86
+ ```python
87
+ import optiland.backend as be
88
+
89
+ be.set_backend("torch")
90
+ be.set_precision("float64")
91
+ be.grad_mode.enable()
92
+ geometry = op.surfaces.surfaces[1].geometry
93
+ geometry.points = geometry.points.detach().clone().requires_grad_(True)
94
+ # trace, compute a merit, merit.backward(); geometry.points.grad holds the gradient
95
+ ```
96
+
97
+ ## What it covers
98
+
99
+ - **Refraction-only lenses whose faces are surfaces of revolution**, one spline span per face,
100
+ from the axis to the rim.
101
+ - **Not** mirrors or total internal reflection, which do not fit a sequential trace; not Optiland's
102
+ non-sequential engine, which has no plugin hook; not faces made of several spans.
103
+
104
+ The reader refuses what it cannot represent, and says why.
105
+
106
+ ## How it is checked
107
+
108
+ On the RR lens of Chaves, *Introduction to Nonimaging Optics*, Example 9.1 (`tests/fixtures/`):
109
+ - the surface reproduces the profile's samples (sag to 1e-15, normals to 1e-13 rad) and its curve
110
+ between them;
111
+ - numpy and torch trace the same rays to 1e-11 (Optiland's solve stops at its own tolerance);
112
+ - the gradient agrees with a central finite difference to 1e-5 relative (1e-6 measured).
113
+
114
+ ```bash
115
+ pip install -e ".[dev]"
116
+ pytest
117
+ ```
118
+
119
+ ## Citing
120
+
121
+ If you use this software, please cite it, and the ray-tracing-shapely project whose profiles it
122
+ reads. `CITATION.cff` carries the metadata for both; GitHub formats it from the *Cite this
123
+ repository* link.
124
+
125
+ This project: [doi:10.5281/zenodo.24416270](https://doi.org/10.5281/zenodo.24416270). That is the
126
+ *concept* DOI, which always resolves to the latest release. Each release also has its own DOI, to
127
+ cite when a result must be pinned to the exact version it came from.
128
+
129
+ ray-tracing-shapely: [doi:10.5281/zenodo.23991020](https://doi.org/10.5281/zenodo.23991020).
130
+
131
+ ## Licence
132
+
133
+ Apache-2.0. See `NOTICE.txt`.
@@ -0,0 +1,10 @@
1
+ optiland_sms/__init__.py,sha256=QQ0wOcvF6JK3eWe0u4XLIidtj9cpPlkC0b26B88hD4s,2635
2
+ optiland_sms/geometry.py,sha256=SpPbOG4xSpRg3VpQ2mBg7KIboPW_HeU4kUKvqFB3wrQ,10751
3
+ optiland_sms/meridian.py,sha256=dWqUHWN3cOvNjQoreQXoAw_Nm4wcdBw0dDiW59EnScY,11801
4
+ optiland_sms/register.py,sha256=ereC-oZneX0Lihhl6ep48Y2sz96Xwwl-ySIeY6ymorU,3075
5
+ optiland_sms-0.1.1.dist-info/licenses/NOTICE.txt,sha256=Yk1xBBA7UhwBmxrhHPM8ta_PJpbVodOZlGWb5JkdArs,516
6
+ optiland_sms-0.1.1.dist-info/METADATA,sha256=VRRl47dyQ4WscmJZaKMRlY9e8CtLq0nu2OFTMDVXV4E,5360
7
+ optiland_sms-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ optiland_sms-0.1.1.dist-info/entry_points.txt,sha256=hOoPtfP1jJxEWz0CIhzItMByuCq5Krio6IIIjFdnT8U,64
9
+ optiland_sms-0.1.1.dist-info/top_level.txt,sha256=EV1J58g9S1pji7b_56OhkGYkk0L-sxJJ8jOlZ5Ydfek,13
10
+ optiland_sms-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [optiland.surfaces]
2
+ sms_spline = optiland_sms.register:register
@@ -0,0 +1,13 @@
1
+ optiland-sms
2
+ Copyright 2026 ray-tracing-shapely authors and contributors
3
+
4
+ This product includes software developed by the ray-tracing-shapely
5
+ authors and contributors, licensed under the Apache License 2.0.
6
+
7
+ This distribution contains no code derived from the Ray Optics
8
+ Simulation project; all 10 of its source files were written for
9
+ this project.
10
+
11
+ It does not depend on the core distribution, ray-tracing-shapely, which
12
+ does contain such code (see its own NOTICE): it reads that project's
13
+ profile.json files only.
@@ -0,0 +1 @@
1
+ optiland_sms