RayCrafter 0.0.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,111 @@
1
+ """The state of the lens bench: the lenses on the axis, the beam and the image plane.
2
+
3
+ All z positions are absolute positions along the optical axis, in mm. The beam comes from
4
+ the left (negative z). These classes hold data only; editing is done by ``OpticalModel``
5
+ (``raycrafter.core.model``) and optics by ``raycrafter.core.optic_builder`` and
6
+ ``raycrafter.core.analysis``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+
13
+ from raycrafter.core.prescription import LensSurface, flipped_prescription, lens_thickness
14
+
15
+ AXIS_START_Z = 0.0 # mm, where the beam starts
16
+
17
+
18
+ @dataclass
19
+ class PlacedLens:
20
+ """One lens on the optical axis: its prescription, position, orientation and size.
21
+
22
+ Attributes
23
+ ----------
24
+ part_number : str
25
+ Catalogue part number, e.g. ``"ACT508-200-A"``.
26
+ surfaces : list of LensSurface
27
+ The prescription in the catalogue orientation (see ``surfaces_in_use`` for the
28
+ current one).
29
+ semi_aperture : float
30
+ Half the clear diameter, in mm.
31
+ z : float
32
+ z of the front vertex, in mm.
33
+ flipped : bool
34
+ True if the lens is turned around relative to the catalogue.
35
+ group_id : int or None
36
+ Lenses that share an id form a Plossl pair and move together.
37
+ is_negative : bool
38
+ True for a diverging lens (negative focal length). These cannot form a Plossl pair.
39
+ """
40
+
41
+ part_number: str
42
+ surfaces: list[LensSurface]
43
+ semi_aperture: float
44
+ z: float
45
+ flipped: bool = False
46
+ group_id: int | None = None
47
+ is_negative: bool = False
48
+
49
+ def surfaces_in_use(self) -> list[LensSurface]:
50
+ """The surfaces in the current orientation."""
51
+ return flipped_prescription(self.surfaces) if self.flipped else self.surfaces
52
+
53
+ def positive_element_is_first(self) -> bool:
54
+ """True if, in the catalogue orientation, the front glass element is the stronger one.
55
+
56
+ Each element's power is approximated by 1/R_front - 1/R_back (the glass index factor
57
+ is positive for both, so it does not change which is larger). For a positive doublet
58
+ the stronger element is the crown.
59
+ """
60
+ glass_surface_indices = [
61
+ index
62
+ for index, surface in enumerate(self.surfaces[:-1])
63
+ if surface.material_after != "air"
64
+ ]
65
+ powers = []
66
+ for index in (glass_surface_indices[0], glass_surface_indices[-1]):
67
+ front, back = self.surfaces[index], self.surfaces[index + 1]
68
+ powers.append(1.0 / front.radius - 1.0 / back.radius)
69
+ return powers[0] > powers[1]
70
+
71
+ @property
72
+ def thickness(self) -> float:
73
+ """Front-vertex to back-vertex distance (mm)."""
74
+ return lens_thickness(self.surfaces)
75
+
76
+ @property
77
+ def back_z(self) -> float:
78
+ """z of the back vertex (mm)."""
79
+ return self.z + self.thickness
80
+
81
+
82
+ @dataclass
83
+ class OpticalState:
84
+ """Everything the user can change: the lenses, the beam and the image plane.
85
+
86
+ Attributes
87
+ ----------
88
+ lenses : list of PlacedLens
89
+ Ordered left to right along the axis.
90
+ next_group_id : int
91
+ The id the next Plossl pair will get.
92
+ beam_diameter : float
93
+ Beam diameter at the first lens, in mm.
94
+ field_angle : float
95
+ Beam angle to the axis, in degrees.
96
+ beam_vergence : float
97
+ Dioptres (1/m): positive is converging, negative diverging, zero collimated.
98
+ image_z : float
99
+ z of the image plane, in mm.
100
+ """
101
+
102
+ lenses: list[PlacedLens] = field(default_factory=list)
103
+ next_group_id: int = 1
104
+ beam_diameter: float = 10.0
105
+ field_angle: float = 0.0
106
+ beam_vergence: float = 0.0
107
+ image_z: float = 310.0
108
+
109
+ def last_back_z(self) -> float:
110
+ """z of the back vertex of the rightmost lens (0 if there are no lenses)."""
111
+ return self.lenses[-1].back_z if self.lenses else AXIS_START_Z
@@ -0,0 +1 @@
1
+ """The PyQt6 + pyqtgraph application. Run it with the ``raycrafter`` command."""
@@ -0,0 +1,260 @@
1
+ """The analysis plots below the side view: spot, through-focus, MTF, ray fan, field curvature.
2
+
3
+ Each panel is a pyqtgraph plot widget with a ``show_result`` method that draws one result
4
+ object from ``raycrafter.core.analysis``. The panels do no optics themselves.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+ import pyqtgraph as pg
11
+ from PyQt6.QtCore import Qt
12
+ from PyQt6.QtWidgets import QTabWidget, QWidget
13
+
14
+ from raycrafter import palette
15
+ from raycrafter.core.analysis import (
16
+ FIELD_CURVATURE_MAX_ANGLE,
17
+ FastTrace,
18
+ FieldCurvatureResult,
19
+ MtfResult,
20
+ RayFanResult,
21
+ ThroughFocusResult,
22
+ airy_radius,
23
+ )
24
+ from raycrafter.core.plot_geometry import ray_fan_limit_um, spot_view_half_width_um
25
+ from raycrafter.gui.style import PLOT_MIN_SIZE_PX, style_plot
26
+
27
+ TITLE_SIZE = "11pt"
28
+
29
+
30
+ def make_tabs(tabs: list[tuple[str, QWidget]]) -> QTabWidget:
31
+ """A tab widget from (label, plot widget) pairs, with the minimum plot size set."""
32
+ tab_widget = QTabWidget()
33
+ tab_bar = tab_widget.tabBar()
34
+ tab_bar.setExpanding(False)
35
+ tab_bar.setDrawBase(False)
36
+
37
+ # Tab labels must never be shortened with "...": switch eliding off and keep scroll arrows
38
+ # away. (Their font size is set on QTabBar itself in the style sheet, not on QTabBar::tab,
39
+ # so the width Qt reserves for a tab is computed from the same font that is painted.)
40
+ tab_bar.setElideMode(Qt.TextElideMode.ElideNone)
41
+ tab_bar.setUsesScrollButtons(False)
42
+ for label, plot_widget in tabs:
43
+ plot_widget.setMinimumSize(*PLOT_MIN_SIZE_PX)
44
+ tab_widget.addTab(plot_widget, label)
45
+ return tab_widget
46
+
47
+
48
+ class SpotPanel(pg.PlotWidget):
49
+ """Spot diagram, each field centred on its own centroid, with the Airy disk dashed.
50
+
51
+ The current-angle spot is blue. When the beam is tilted the 0 degree spot is drawn too
52
+ (orange, underneath) so the off-axis degradation can be compared at a glance.
53
+ """
54
+
55
+ def __init__(self) -> None:
56
+ super().__init__()
57
+ style_plot(self, "x (um)", "y (um)")
58
+ plot = self.getPlotItem()
59
+ plot.setAspectLocked(True)
60
+ plot.addLine(x=0, pen=pg.mkPen("#dee2e6"))
61
+ plot.addLine(y=0, pen=pg.mkPen("#dee2e6"))
62
+ self.airy_curve = pg.PlotCurveItem(
63
+ pen=pg.mkPen(palette.AIRY, width=1.2, style=Qt.PenStyle.DashLine)
64
+ )
65
+ self.on_axis_scatter = pg.ScatterPlotItem(
66
+ size=5, pen=None, brush=pg.mkBrush(palette.ON_AXIS)
67
+ )
68
+ self.current_scatter = pg.ScatterPlotItem(
69
+ size=5, pen=None, brush=pg.mkBrush(palette.TANGENTIAL)
70
+ )
71
+ for item in (self.airy_curve, self.on_axis_scatter, self.current_scatter):
72
+ plot.addItem(item)
73
+
74
+ def show_result(self, fast_trace: FastTrace, field_angle: float) -> None:
75
+ """Draw the spots (micrometres about each centroid), the Airy disk and the RMS radii."""
76
+ spot, on_axis_spot = fast_trace.spot, fast_trace.on_axis_spot
77
+ self.current_scatter.setData(spot.x * 1000.0, spot.y * 1000.0)
78
+ if on_axis_spot is not None:
79
+ self.on_axis_scatter.setData(on_axis_spot.x * 1000.0, on_axis_spot.y * 1000.0)
80
+ else:
81
+ self.on_axis_scatter.setData([], [])
82
+
83
+ airy = airy_radius(spot.numerical_aperture)
84
+ if airy is None:
85
+ self.airy_curve.setData([], [])
86
+ else:
87
+ airy_um = airy * 1000.0
88
+ angles = np.linspace(0.0, 2.0 * np.pi, 120)
89
+ self.airy_curve.setData(airy_um * np.cos(angles), airy_um * np.sin(angles))
90
+
91
+ half_width = spot_view_half_width_um(spot, on_axis_spot)
92
+ plot = self.getPlotItem()
93
+ plot.setRange(xRange=(-half_width, half_width), yRange=(-half_width, half_width), padding=0)
94
+
95
+ # The title doubles as the legend: each RMS radius is written in its spot colour.
96
+ if on_axis_spot is None:
97
+ title = f"RMS radius {spot.rms_radius * 1000:.2f} um"
98
+ else:
99
+ title = (
100
+ f'<span style="color:{palette.TANGENTIAL}">{field_angle:+.1f} deg: '
101
+ f"{spot.rms_radius * 1000:.2f} um</span>&nbsp;&nbsp;"
102
+ f'<span style="color:{palette.ON_AXIS}">0 deg: '
103
+ f"{on_axis_spot.rms_radius * 1000:.2f} um</span>"
104
+ )
105
+ plot.setTitle(title, size="10pt")
106
+
107
+
108
+ class ThroughFocusPanel(pg.PlotWidget):
109
+ """RMS spot radius against image plane position.
110
+
111
+ Green is the current image plane, the dotted blue line the best focus and the dashed
112
+ grey line the Airy radius.
113
+ """
114
+
115
+ def __init__(self) -> None:
116
+ super().__init__()
117
+ style_plot(self, "image plane offset (mm)", "RMS radius (um)")
118
+ plot = self.getPlotItem()
119
+ plot.setTitle("Through-focus RMS radius", size=TITLE_SIZE)
120
+ plot.addLine(x=0, pen=pg.mkPen(palette.IMAGE, width=2))
121
+ self.best_focus_line = plot.addLine(
122
+ x=0, pen=pg.mkPen(palette.TANGENTIAL, width=1, style=Qt.PenStyle.DotLine)
123
+ )
124
+ self.airy_line = plot.addLine(
125
+ y=0,
126
+ pen=pg.mkPen(palette.AIRY, width=1.2, style=Qt.PenStyle.DashLine),
127
+ label="Airy radius",
128
+ labelOpts={"position": 0.12, "color": palette.AIRY},
129
+ )
130
+ self.on_axis_curve = plot.plot(pen=pg.mkPen(palette.ON_AXIS, width=2))
131
+ self.current_curve = plot.plot(pen=pg.mkPen(palette.TANGENTIAL, width=2))
132
+
133
+ def show_result(self, result: ThroughFocusResult) -> None:
134
+ """Draw RMS radius against offset, with the best focus and the Airy radius marked."""
135
+ rms_current_um = result.rms_current * 1000.0
136
+ self.current_curve.setData(result.offsets, rms_current_um)
137
+ curve_maximum_um = rms_current_um.max()
138
+
139
+ if result.rms_on_axis is not None:
140
+ rms_on_axis_um = result.rms_on_axis * 1000.0
141
+ self.on_axis_curve.setData(result.offsets, rms_on_axis_um)
142
+ curve_maximum_um = max(curve_maximum_um, rms_on_axis_um.max())
143
+ else:
144
+ self.on_axis_curve.setData([], [])
145
+
146
+ self.best_focus_line.setValue(result.best_offset)
147
+
148
+ # Show the Airy radius line unless it is far above the curve.
149
+ y_maximum_um = curve_maximum_um
150
+ self.airy_line.setVisible(result.airy_radius is not None)
151
+ if result.airy_radius is not None:
152
+ airy_um = result.airy_radius * 1000.0
153
+ self.airy_line.setValue(airy_um)
154
+ y_maximum_um = max(curve_maximum_um, min(airy_um, 3.0 * curve_maximum_um))
155
+
156
+ plot = self.getPlotItem()
157
+ plot.setXRange(result.offsets[0], result.offsets[-1], padding=0)
158
+ plot.setYRange(0, y_maximum_um * 1.08, padding=0)
159
+
160
+
161
+ class MtfPanel(pg.PlotWidget):
162
+ """Tangential and sagittal MTF, with the diffraction limit."""
163
+
164
+ def __init__(self) -> None:
165
+ super().__init__()
166
+ style_plot(self, "spatial frequency (cycles/mm)", "modulation")
167
+ plot = self.getPlotItem()
168
+ plot.setTitle("MTF", size=TITLE_SIZE)
169
+ plot.setYRange(0, 1.02, padding=0)
170
+ plot.addLegend(offset=(-5, 5))
171
+ self.limit_curve = plot.plot(
172
+ pen=pg.mkPen(palette.AIRY, width=1.2, style=Qt.PenStyle.DashLine),
173
+ name="diffraction limit",
174
+ )
175
+ self.tangential_curve = plot.plot(
176
+ pen=pg.mkPen(palette.TANGENTIAL, width=2), name="tangential"
177
+ )
178
+ self.sagittal_curve = plot.plot(pen=pg.mkPen(palette.SAGITTAL, width=2), name="sagittal")
179
+
180
+ def show_result(self, mtf: MtfResult, field_angle: float) -> None:
181
+ """Draw the MTF curves computed at ``field_angle`` degrees."""
182
+ self.limit_curve.setData(mtf.frequency, mtf.diffraction_limit)
183
+ self.tangential_curve.setData(mtf.frequency, mtf.tangential)
184
+ self.sagittal_curve.setData(mtf.frequency, mtf.sagittal)
185
+ plot = self.getPlotItem()
186
+ plot.setTitle(f"MTF at {field_angle:+.1f} deg", size=TITLE_SIZE)
187
+ plot.setXRange(0, mtf.frequency[-1], padding=0)
188
+
189
+
190
+ class RayFanPanel(pg.PlotWidget):
191
+ """Image-plane error against pupil coordinate for the tangential and sagittal fans."""
192
+
193
+ def __init__(self) -> None:
194
+ super().__init__()
195
+ style_plot(self, "pupil coordinate", "image plane error (um)")
196
+ plot = self.getPlotItem()
197
+ plot.setTitle("Ray fan", size=TITLE_SIZE)
198
+ plot.setXRange(-1, 1, padding=0.02)
199
+ plot.addLegend(offset=(-5, 5))
200
+ plot.addLine(y=0, pen=pg.mkPen(palette.FAINT))
201
+ self.tangential_curve = plot.plot(
202
+ pen=pg.mkPen(palette.TANGENTIAL, width=2), name="tangential"
203
+ )
204
+ self.sagittal_curve = plot.plot(
205
+ pen=pg.mkPen(palette.SAGITTAL, width=2, style=Qt.PenStyle.DashLine), name="sagittal"
206
+ )
207
+
208
+ def show_result(self, fan: RayFanResult, field_angle: float) -> None:
209
+ """Draw the ray fan (micrometres) computed at ``field_angle`` degrees."""
210
+ self.tangential_curve.setData(fan.pupil, fan.tangential_error * 1000.0)
211
+ self.sagittal_curve.setData(fan.pupil, fan.sagittal_error * 1000.0)
212
+ plot = self.getPlotItem()
213
+ plot.setTitle(f"Ray fan at {field_angle:+.1f} deg", size=TITLE_SIZE)
214
+
215
+ largest_error_mm = max(np.abs(fan.tangential_error).max(), np.abs(fan.sagittal_error).max())
216
+ limit_um = ray_fan_limit_um(largest_error_mm)
217
+ plot.setYRange(-limit_um, limit_um, padding=0)
218
+
219
+
220
+ class FieldCurvaturePanel(pg.PlotWidget):
221
+ """Best-focus shift against field angle, relative to the image plane."""
222
+
223
+ def __init__(self) -> None:
224
+ super().__init__()
225
+ style_plot(self, "focus shift from image plane (mm)", "field angle (deg)")
226
+ plot = self.getPlotItem()
227
+ plot.setTitle("Best focus against field angle", size=TITLE_SIZE)
228
+ plot.setYRange(0, FIELD_CURVATURE_MAX_ANGLE, padding=0.02)
229
+ plot.addLegend(offset=(-5, 5))
230
+ plot.addLine(x=0, pen=pg.mkPen(palette.IMAGE, width=2))
231
+ self.current_angle_line = plot.addLine(
232
+ y=0, pen=pg.mkPen(palette.FAINT, style=Qt.PenStyle.DashLine)
233
+ )
234
+ self.tangential_curve = plot.plot(
235
+ pen=pg.mkPen(palette.TANGENTIAL, width=2),
236
+ symbol="o",
237
+ symbolSize=5,
238
+ symbolBrush=palette.TANGENTIAL,
239
+ symbolPen=None,
240
+ name="tangential",
241
+ )
242
+ self.sagittal_curve = plot.plot(
243
+ pen=pg.mkPen(palette.SAGITTAL, width=2, style=Qt.PenStyle.DashLine),
244
+ symbol="s",
245
+ symbolSize=5,
246
+ symbolBrush=palette.SAGITTAL,
247
+ symbolPen=None,
248
+ name="sagittal",
249
+ )
250
+
251
+ def show_result(self, curvature: FieldCurvatureResult, field_angle: float) -> None:
252
+ """Draw the curves; a dashed line marks the current beam angle."""
253
+ self.tangential_curve.setData(curvature.tangential_shift, curvature.angles)
254
+ self.sagittal_curve.setData(curvature.sagittal_shift, curvature.angles)
255
+ self.current_angle_line.setValue(abs(field_angle))
256
+
257
+ largest_shift = max(
258
+ np.abs(curvature.tangential_shift).max(), np.abs(curvature.sagittal_shift).max(), 0.5
259
+ )
260
+ self.getPlotItem().setXRange(-largest_shift * 1.1, largest_shift * 1.1, padding=0)
raycrafter/gui/app.py ADDED
@@ -0,0 +1,24 @@
1
+ """Start the RayCrafter GUI. Installed as the ``raycrafter`` command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from PyQt6.QtWidgets import QApplication
8
+
9
+ from raycrafter.gui.main_window import MainWindow
10
+ from raycrafter.gui.style import make_app_icon
11
+
12
+
13
+ def main() -> None:
14
+ """Create the Qt application, show the main window and run until it is closed."""
15
+ app = QApplication(sys.argv)
16
+ app.setApplicationName("RayCrafter")
17
+ app.setWindowIcon(make_app_icon())
18
+ window = MainWindow()
19
+ window.show()
20
+ sys.exit(app.exec())
21
+
22
+
23
+ if __name__ == "__main__":
24
+ main()