lsurf 1.0.0__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.
Files changed (180) hide show
  1. lsurf/__init__.py +471 -0
  2. lsurf/analysis/__init__.py +107 -0
  3. lsurf/analysis/healpix_utils.py +418 -0
  4. lsurf/analysis/sphere_viz.py +1280 -0
  5. lsurf/cli/__init__.py +48 -0
  6. lsurf/cli/build.py +398 -0
  7. lsurf/cli/config_schema.py +318 -0
  8. lsurf/cli/gui_cmd.py +76 -0
  9. lsurf/cli/interactive.py +850 -0
  10. lsurf/cli/main.py +81 -0
  11. lsurf/cli/run.py +806 -0
  12. lsurf/detectors/__init__.py +266 -0
  13. lsurf/detectors/analysis.py +289 -0
  14. lsurf/detectors/base.py +284 -0
  15. lsurf/detectors/constant_size_rings.py +485 -0
  16. lsurf/detectors/directional.py +45 -0
  17. lsurf/detectors/extended/__init__.py +73 -0
  18. lsurf/detectors/extended/local_sphere.py +353 -0
  19. lsurf/detectors/extended/recording_sphere.py +368 -0
  20. lsurf/detectors/planar.py +45 -0
  21. lsurf/detectors/protocol.py +187 -0
  22. lsurf/detectors/recording_spheres.py +63 -0
  23. lsurf/detectors/results.py +1140 -0
  24. lsurf/detectors/small/__init__.py +79 -0
  25. lsurf/detectors/small/directional.py +330 -0
  26. lsurf/detectors/small/planar.py +401 -0
  27. lsurf/detectors/small/spherical.py +450 -0
  28. lsurf/detectors/spherical.py +45 -0
  29. lsurf/geometry/__init__.py +199 -0
  30. lsurf/geometry/builder.py +478 -0
  31. lsurf/geometry/cell.py +228 -0
  32. lsurf/geometry/cell_geometry.py +247 -0
  33. lsurf/geometry/detector_arrays.py +1785 -0
  34. lsurf/geometry/geometry.py +222 -0
  35. lsurf/geometry/surface_analysis.py +375 -0
  36. lsurf/geometry/validation.py +91 -0
  37. lsurf/gui/__init__.py +51 -0
  38. lsurf/gui/app.py +903 -0
  39. lsurf/gui/core/__init__.py +39 -0
  40. lsurf/gui/core/scene.py +343 -0
  41. lsurf/gui/core/simulation.py +264 -0
  42. lsurf/gui/renderers/__init__.py +40 -0
  43. lsurf/gui/renderers/ray_renderer.py +353 -0
  44. lsurf/gui/renderers/source_renderer.py +505 -0
  45. lsurf/gui/renderers/surface_renderer.py +477 -0
  46. lsurf/gui/views/__init__.py +48 -0
  47. lsurf/gui/views/config_editor.py +3199 -0
  48. lsurf/gui/views/properties.py +257 -0
  49. lsurf/gui/views/results.py +291 -0
  50. lsurf/gui/views/scene_tree.py +180 -0
  51. lsurf/gui/views/viewport_3d.py +555 -0
  52. lsurf/gui/views/visualizations.py +712 -0
  53. lsurf/materials/__init__.py +169 -0
  54. lsurf/materials/base/__init__.py +64 -0
  55. lsurf/materials/base/full_inhomogeneous.py +208 -0
  56. lsurf/materials/base/grid_inhomogeneous.py +319 -0
  57. lsurf/materials/base/homogeneous.py +342 -0
  58. lsurf/materials/base/material_field.py +527 -0
  59. lsurf/materials/base/simple_inhomogeneous.py +418 -0
  60. lsurf/materials/base/spectral_inhomogeneous.py +497 -0
  61. lsurf/materials/implementations/__init__.py +120 -0
  62. lsurf/materials/implementations/data/alpha_values_typical_atmosphere_updated.txt +24 -0
  63. lsurf/materials/implementations/duct_atmosphere.py +390 -0
  64. lsurf/materials/implementations/exponential_atmosphere.py +435 -0
  65. lsurf/materials/implementations/gaussian_lens.py +120 -0
  66. lsurf/materials/implementations/interpolated_data.py +123 -0
  67. lsurf/materials/implementations/layered_atmosphere.py +134 -0
  68. lsurf/materials/implementations/linear_gradient.py +109 -0
  69. lsurf/materials/implementations/linsley_atmosphere.py +764 -0
  70. lsurf/materials/implementations/standard_materials.py +126 -0
  71. lsurf/materials/implementations/turbulent_atmosphere.py +135 -0
  72. lsurf/materials/implementations/us_standard_atmosphere.py +149 -0
  73. lsurf/materials/utils/__init__.py +77 -0
  74. lsurf/materials/utils/constants.py +45 -0
  75. lsurf/materials/utils/device_functions.py +117 -0
  76. lsurf/materials/utils/dispersion.py +160 -0
  77. lsurf/materials/utils/factories.py +142 -0
  78. lsurf/propagation/__init__.py +91 -0
  79. lsurf/propagation/detector_gpu.py +67 -0
  80. lsurf/propagation/gpu_device_rays.py +294 -0
  81. lsurf/propagation/kernels/__init__.py +175 -0
  82. lsurf/propagation/kernels/absorption/__init__.py +61 -0
  83. lsurf/propagation/kernels/absorption/grid.py +240 -0
  84. lsurf/propagation/kernels/absorption/simple.py +232 -0
  85. lsurf/propagation/kernels/absorption/spectral.py +410 -0
  86. lsurf/propagation/kernels/detection/__init__.py +64 -0
  87. lsurf/propagation/kernels/detection/protocol.py +102 -0
  88. lsurf/propagation/kernels/detection/spherical.py +255 -0
  89. lsurf/propagation/kernels/device_functions.py +790 -0
  90. lsurf/propagation/kernels/fresnel/__init__.py +64 -0
  91. lsurf/propagation/kernels/fresnel/protocol.py +97 -0
  92. lsurf/propagation/kernels/fresnel/standard.py +258 -0
  93. lsurf/propagation/kernels/intersection/__init__.py +79 -0
  94. lsurf/propagation/kernels/intersection/annular_plane.py +207 -0
  95. lsurf/propagation/kernels/intersection/bounded_plane.py +205 -0
  96. lsurf/propagation/kernels/intersection/plane.py +166 -0
  97. lsurf/propagation/kernels/intersection/protocol.py +95 -0
  98. lsurf/propagation/kernels/intersection/signed_distance.py +742 -0
  99. lsurf/propagation/kernels/intersection/sphere.py +190 -0
  100. lsurf/propagation/kernels/propagation/__init__.py +85 -0
  101. lsurf/propagation/kernels/propagation/grid.py +527 -0
  102. lsurf/propagation/kernels/propagation/protocol.py +105 -0
  103. lsurf/propagation/kernels/propagation/simple.py +460 -0
  104. lsurf/propagation/kernels/propagation/spectral.py +875 -0
  105. lsurf/propagation/kernels/registry.py +331 -0
  106. lsurf/propagation/kernels/surface/__init__.py +72 -0
  107. lsurf/propagation/kernels/surface/bisection.py +232 -0
  108. lsurf/propagation/kernels/surface/detection.py +402 -0
  109. lsurf/propagation/kernels/surface/reduction.py +166 -0
  110. lsurf/propagation/propagator_protocol.py +222 -0
  111. lsurf/propagation/propagators/__init__.py +101 -0
  112. lsurf/propagation/propagators/detector_handler.py +354 -0
  113. lsurf/propagation/propagators/factory.py +200 -0
  114. lsurf/propagation/propagators/fresnel_handler.py +305 -0
  115. lsurf/propagation/propagators/gpu_gradient.py +566 -0
  116. lsurf/propagation/propagators/gpu_surface_propagator.py +707 -0
  117. lsurf/propagation/propagators/gradient.py +429 -0
  118. lsurf/propagation/propagators/intersection_handler.py +327 -0
  119. lsurf/propagation/propagators/material_propagator.py +398 -0
  120. lsurf/propagation/propagators/signed_distance_handler.py +522 -0
  121. lsurf/propagation/propagators/spectral_gpu_gradient.py +553 -0
  122. lsurf/propagation/propagators/surface_interaction.py +616 -0
  123. lsurf/propagation/propagators/surface_propagator.py +719 -0
  124. lsurf/py.typed +1 -0
  125. lsurf/simulation/__init__.py +70 -0
  126. lsurf/simulation/config.py +164 -0
  127. lsurf/simulation/orchestrator.py +462 -0
  128. lsurf/simulation/result.py +299 -0
  129. lsurf/simulation/simulation.py +262 -0
  130. lsurf/sources/__init__.py +128 -0
  131. lsurf/sources/base.py +264 -0
  132. lsurf/sources/collimated.py +252 -0
  133. lsurf/sources/custom.py +409 -0
  134. lsurf/sources/diverging.py +228 -0
  135. lsurf/sources/gaussian.py +272 -0
  136. lsurf/sources/parallel_from_positions.py +197 -0
  137. lsurf/sources/point.py +172 -0
  138. lsurf/sources/uniform_diverging.py +258 -0
  139. lsurf/surfaces/__init__.py +184 -0
  140. lsurf/surfaces/cpu/__init__.py +50 -0
  141. lsurf/surfaces/cpu/curved_wave.py +463 -0
  142. lsurf/surfaces/cpu/gerstner_wave.py +381 -0
  143. lsurf/surfaces/cpu/wave_params.py +118 -0
  144. lsurf/surfaces/gpu/__init__.py +72 -0
  145. lsurf/surfaces/gpu/annular_plane.py +453 -0
  146. lsurf/surfaces/gpu/bounded_plane.py +390 -0
  147. lsurf/surfaces/gpu/curved_wave.py +483 -0
  148. lsurf/surfaces/gpu/gerstner_wave.py +377 -0
  149. lsurf/surfaces/gpu/multi_curved_wave.py +520 -0
  150. lsurf/surfaces/gpu/plane.py +299 -0
  151. lsurf/surfaces/gpu/recording_sphere.py +587 -0
  152. lsurf/surfaces/gpu/sphere.py +311 -0
  153. lsurf/surfaces/protocol.py +336 -0
  154. lsurf/surfaces/registry.py +373 -0
  155. lsurf/utilities/__init__.py +175 -0
  156. lsurf/utilities/detector_analysis.py +814 -0
  157. lsurf/utilities/fresnel.py +628 -0
  158. lsurf/utilities/interactions.py +1215 -0
  159. lsurf/utilities/propagation.py +602 -0
  160. lsurf/utilities/ray_data.py +532 -0
  161. lsurf/utilities/recording_sphere.py +745 -0
  162. lsurf/utilities/time_spread.py +463 -0
  163. lsurf/visualization/__init__.py +329 -0
  164. lsurf/visualization/absorption_plots.py +334 -0
  165. lsurf/visualization/atmospheric_plots.py +754 -0
  166. lsurf/visualization/common.py +348 -0
  167. lsurf/visualization/detector_plots.py +1350 -0
  168. lsurf/visualization/detector_sphere_plots.py +1173 -0
  169. lsurf/visualization/fresnel_plots.py +1061 -0
  170. lsurf/visualization/ocean_simulation_plots.py +999 -0
  171. lsurf/visualization/polarization_plots.py +916 -0
  172. lsurf/visualization/raytracing_plots.py +1521 -0
  173. lsurf/visualization/ring_detector_plots.py +1867 -0
  174. lsurf/visualization/time_spread_plots.py +531 -0
  175. lsurf-1.0.0.dist-info/METADATA +381 -0
  176. lsurf-1.0.0.dist-info/RECORD +180 -0
  177. lsurf-1.0.0.dist-info/WHEEL +5 -0
  178. lsurf-1.0.0.dist-info/entry_points.txt +2 -0
  179. lsurf-1.0.0.dist-info/licenses/LICENSE +32 -0
  180. lsurf-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,532 @@
1
+ # The Clear BSD License
2
+ #
3
+ # Copyright (c) 2026 Tobias Heibges
4
+ # All rights reserved.
5
+ #
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted (subject to the limitations in the disclaimer
8
+ # below) provided that the following conditions are met:
9
+ #
10
+ # * Redistributions of source code must retain the above copyright notice,
11
+ # this list of conditions and the following disclaimer.
12
+ #
13
+ # * Redistributions in binary form must reproduce the above copyright
14
+ # notice, this list of conditions and the following disclaimer in the
15
+ # documentation and/or other materials provided with the distribution.
16
+ #
17
+ # * Neither the name of the copyright holder nor the names of its
18
+ # contributors may be used to endorse or promote products derived from this
19
+ # software without specific prior written permission.
20
+ #
21
+ # NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
22
+ # THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
23
+ # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
25
+ # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
26
+ # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27
+ # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28
+ # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
29
+ # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
30
+ # IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
+ # POSSIBILITY OF SUCH DAMAGE.
33
+
34
+ """
35
+ Ray Data Structures for GPU Raytracing
36
+
37
+ This module defines the core data structures for representing rays in the
38
+ simulation, including position, direction, optical properties, and state tracking.
39
+ """
40
+
41
+ from dataclasses import dataclass
42
+ from typing import NamedTuple
43
+
44
+ import numpy as np
45
+ import numpy.typing as npt
46
+
47
+ # Type aliases for clarity
48
+ Float32Array = npt.NDArray[np.float32]
49
+ BoolArray = npt.NDArray[np.bool_]
50
+ Int32Array = npt.NDArray[np.int32]
51
+
52
+
53
+ @dataclass
54
+ class RayBatch:
55
+ """
56
+ Structure-of-Arrays (SoA) layout for efficient GPU processing of ray batches.
57
+
58
+ All arrays have shape (N,) where N is the number of rays, except positions
59
+ and directions which have shape (N, 3).
60
+
61
+ This layout maximizes memory coalescing on GPU and enables efficient SIMD
62
+ operations on CPU.
63
+
64
+ Attributes
65
+ ----------
66
+ positions : Float32Array
67
+ Ray origin positions, shape (N, 3), units: meters
68
+ [x0, y0, z0; x1, y1, z1; ...]
69
+ directions : Float32Array
70
+ Ray direction unit vectors, shape (N, 3), dimensionless
71
+ [dx0, dy0, dz0; dx1, dy1, dz1; ...]
72
+ wavelengths : Float32Array
73
+ Wavelengths, shape (N,), units: meters
74
+ intensities : Float32Array
75
+ Current ray intensities/powers, shape (N,), units: W or arbitrary
76
+ optical_path_lengths : Float32Array
77
+ Accumulated optical path length ∫n(s)ds, shape (N,), units: meters
78
+ geometric_path_lengths : Float32Array
79
+ Accumulated geometric path length ∫ds, shape (N,), units: meters
80
+ accumulated_time : Float32Array
81
+ Accumulated propagation time, shape (N,), units: seconds
82
+ generations : Int32Array
83
+ Scattering generation (0=primary, 1=first scatter, etc.), shape (N,)
84
+ domain_ids : Int32Array
85
+ Current domain ID for each ray, shape (N,)
86
+ active : BoolArray
87
+ Whether ray is still active (not terminated), shape (N,)
88
+ polarization_s : Optional[Float32Array]
89
+ S-polarization component (optional), shape (N,)
90
+ polarization_p : Optional[Float32Array]
91
+ P-polarization component (optional), shape (N,)
92
+ polarization_vector : Optional[Float32Array]
93
+ 3D polarization vector (electric field direction), shape (N, 3)
94
+ Unit vector perpendicular to ray direction representing E-field orientation.
95
+ Used for tracking polarization state through reflections/refractions.
96
+ phase : Optional[Float32Array]
97
+ Phase in radians (for coherent simulations), shape (N,)
98
+ optical_depth : Optional[Float32Array]
99
+ Accumulated optical depth τ = ∫α·ds, shape (N,), dimensionless
100
+ Used for Beer-Lambert absorption tracking. τ = -ln(I/I₀)
101
+
102
+ Notes
103
+ -----
104
+ The SoA layout enables efficient GPU memory access patterns. For example,
105
+ all x-coordinates are contiguous in memory, allowing coalesced reads.
106
+
107
+ References
108
+ ----------
109
+ .. [1] https://en.wikipedia.org/wiki/AoS_and_SoA
110
+ """
111
+
112
+ positions: Float32Array
113
+ directions: Float32Array
114
+ wavelengths: Float32Array
115
+ intensities: Float32Array
116
+ optical_path_lengths: Float32Array
117
+ geometric_path_lengths: Float32Array
118
+ accumulated_time: Float32Array
119
+ generations: Int32Array
120
+ domain_ids: Int32Array
121
+ active: BoolArray
122
+ polarization_s: Float32Array | None = None
123
+ polarization_p: Float32Array | None = None
124
+ polarization_vector: Float32Array | None = None
125
+ phase: Float32Array | None = None
126
+ optical_depth: Float32Array | None = None
127
+
128
+ def __post_init__(self) -> None:
129
+ """Validate array shapes after initialization."""
130
+ n_rays = len(self.positions)
131
+
132
+ # Validate shapes
133
+ assert self.positions.shape == (
134
+ n_rays,
135
+ 3,
136
+ ), f"positions must have shape (N, 3), got {self.positions.shape}"
137
+ assert self.directions.shape == (
138
+ n_rays,
139
+ 3,
140
+ ), f"directions must have shape (N, 3), got {self.directions.shape}"
141
+ assert self.wavelengths.shape == (
142
+ n_rays,
143
+ ), f"wavelengths must have shape (N,), got {self.wavelengths.shape}"
144
+ assert self.intensities.shape == (
145
+ n_rays,
146
+ ), f"intensities must have shape (N,), got {self.intensities.shape}"
147
+ assert self.optical_path_lengths.shape == (
148
+ n_rays,
149
+ ), f"optical_path_lengths must have shape (N,), got {self.optical_path_lengths.shape}"
150
+ assert self.geometric_path_lengths.shape == (
151
+ n_rays,
152
+ ), f"geometric_path_lengths must have shape (N,), got {self.geometric_path_lengths.shape}"
153
+ assert self.accumulated_time.shape == (
154
+ n_rays,
155
+ ), f"accumulated_time must have shape (N,), got {self.accumulated_time.shape}"
156
+ assert self.generations.shape == (
157
+ n_rays,
158
+ ), f"generations must have shape (N,), got {self.generations.shape}"
159
+ assert self.domain_ids.shape == (
160
+ n_rays,
161
+ ), f"domain_ids must have shape (N,), got {self.domain_ids.shape}"
162
+ assert self.active.shape == (
163
+ n_rays,
164
+ ), f"active must have shape (N,), got {self.active.shape}"
165
+
166
+ # Validate dtypes
167
+ assert self.positions.dtype == np.float32
168
+ assert self.directions.dtype == np.float32
169
+ assert self.wavelengths.dtype == np.float32
170
+ assert self.intensities.dtype == np.float32
171
+ assert self.optical_path_lengths.dtype == np.float32
172
+ assert self.geometric_path_lengths.dtype == np.float32
173
+ assert self.accumulated_time.dtype == np.float32
174
+ assert self.generations.dtype == np.int32
175
+ assert self.domain_ids.dtype == np.int32
176
+ assert self.active.dtype == np.bool_
177
+
178
+ # Validate optional arrays
179
+ if self.polarization_s is not None:
180
+ assert self.polarization_s.shape == (n_rays,)
181
+ assert self.polarization_s.dtype == np.float32
182
+ if self.polarization_p is not None:
183
+ assert self.polarization_p.shape == (n_rays,)
184
+ assert self.polarization_p.dtype == np.float32
185
+ if self.polarization_vector is not None:
186
+ assert self.polarization_vector.shape == (
187
+ n_rays,
188
+ 3,
189
+ ), f"polarization_vector must have shape (N, 3), got {self.polarization_vector.shape}"
190
+ assert self.polarization_vector.dtype == np.float32
191
+ if self.phase is not None:
192
+ assert self.phase.shape == (n_rays,)
193
+ assert self.phase.dtype == np.float32
194
+ if self.optical_depth is not None:
195
+ assert self.optical_depth.shape == (n_rays,)
196
+ assert self.optical_depth.dtype == np.float32
197
+
198
+ @property
199
+ def num_rays(self) -> int:
200
+ """Total number of rays in batch."""
201
+ return len(self.positions)
202
+
203
+ @property
204
+ def num_active(self) -> int:
205
+ """Number of currently active rays."""
206
+ return int(np.sum(self.active))
207
+
208
+ def normalize_directions(self) -> None:
209
+ """Normalize all direction vectors to unit length in-place."""
210
+ norms = np.linalg.norm(self.directions, axis=1, keepdims=True)
211
+ norms = np.maximum(norms, 1e-12) # Avoid division by zero
212
+ self.directions /= norms
213
+
214
+ def compact(self) -> "RayBatch":
215
+ """
216
+ Remove inactive rays to reduce memory and computation.
217
+
218
+ Returns
219
+ -------
220
+ RayBatch
221
+ New batch containing only active rays
222
+
223
+ Notes
224
+ -----
225
+ This operation is called "stream compaction" in GPU programming.
226
+ Useful for maintaining efficiency as rays terminate.
227
+ """
228
+ mask = self.active
229
+
230
+ return RayBatch(
231
+ positions=self.positions[mask].copy(),
232
+ directions=self.directions[mask].copy(),
233
+ wavelengths=self.wavelengths[mask].copy(),
234
+ intensities=self.intensities[mask].copy(),
235
+ optical_path_lengths=self.optical_path_lengths[mask].copy(),
236
+ geometric_path_lengths=self.geometric_path_lengths[mask].copy(),
237
+ accumulated_time=self.accumulated_time[mask].copy(),
238
+ generations=self.generations[mask].copy(),
239
+ domain_ids=self.domain_ids[mask].copy(),
240
+ active=self.active[mask].copy(),
241
+ polarization_s=(
242
+ self.polarization_s[mask].copy()
243
+ if self.polarization_s is not None
244
+ else None
245
+ ),
246
+ polarization_p=(
247
+ self.polarization_p[mask].copy()
248
+ if self.polarization_p is not None
249
+ else None
250
+ ),
251
+ polarization_vector=(
252
+ self.polarization_vector[mask].copy()
253
+ if self.polarization_vector is not None
254
+ else None
255
+ ),
256
+ phase=self.phase[mask].copy() if self.phase is not None else None,
257
+ optical_depth=(
258
+ self.optical_depth[mask].copy()
259
+ if self.optical_depth is not None
260
+ else None
261
+ ),
262
+ )
263
+
264
+ def clone(self) -> "RayBatch":
265
+ """Create a deep copy of the ray batch."""
266
+ return RayBatch(
267
+ positions=self.positions.copy(),
268
+ directions=self.directions.copy(),
269
+ wavelengths=self.wavelengths.copy(),
270
+ intensities=self.intensities.copy(),
271
+ optical_path_lengths=self.optical_path_lengths.copy(),
272
+ geometric_path_lengths=self.geometric_path_lengths.copy(),
273
+ accumulated_time=self.accumulated_time.copy(),
274
+ generations=self.generations.copy(),
275
+ domain_ids=self.domain_ids.copy(),
276
+ active=self.active.copy(),
277
+ polarization_s=(
278
+ self.polarization_s.copy() if self.polarization_s is not None else None
279
+ ),
280
+ polarization_p=(
281
+ self.polarization_p.copy() if self.polarization_p is not None else None
282
+ ),
283
+ polarization_vector=(
284
+ self.polarization_vector.copy()
285
+ if self.polarization_vector is not None
286
+ else None
287
+ ),
288
+ phase=self.phase.copy() if self.phase is not None else None,
289
+ optical_depth=(
290
+ self.optical_depth.copy() if self.optical_depth is not None else None
291
+ ),
292
+ )
293
+
294
+
295
+ class RayStatistics(NamedTuple):
296
+ """
297
+ Statistical summary of ray batch state.
298
+
299
+ Attributes
300
+ ----------
301
+ total_rays : int
302
+ Total number of rays (active + inactive)
303
+ active_rays : int
304
+ Number of active rays
305
+ mean_intensity : float
306
+ Mean intensity of active rays
307
+ total_power : float
308
+ Sum of intensities of all active rays
309
+ mean_optical_path : float
310
+ Mean optical path length of active rays
311
+ mean_generation : float
312
+ Mean scattering generation of active rays
313
+ max_generation : int
314
+ Maximum scattering generation
315
+ """
316
+
317
+ total_rays: int
318
+ active_rays: int
319
+ mean_intensity: float
320
+ total_power: float
321
+ mean_optical_path: float
322
+ mean_generation: float
323
+ max_generation: int
324
+
325
+
326
+ def create_ray_batch(
327
+ num_rays: int,
328
+ enable_polarization: bool = False,
329
+ enable_polarization_vector: bool = False,
330
+ enable_phase: bool = False,
331
+ enable_optical_depth: bool = False,
332
+ ) -> RayBatch:
333
+ """
334
+ Create an empty ray batch with zero-initialized arrays.
335
+
336
+ Parameters
337
+ ----------
338
+ num_rays : int
339
+ Number of rays to allocate
340
+ enable_polarization : bool, optional
341
+ Whether to allocate scalar polarization arrays (s and p components)
342
+ enable_polarization_vector : bool, optional
343
+ Whether to allocate 3D polarization vector array
344
+ enable_phase : bool, optional
345
+ Whether to allocate phase array
346
+ enable_optical_depth : bool, optional
347
+ Whether to allocate optical depth array for absorption tracking
348
+
349
+ Returns
350
+ -------
351
+ RayBatch
352
+ Initialized ray batch with all fields set to zero/false
353
+ """
354
+ positions = np.zeros((num_rays, 3), dtype=np.float32)
355
+ directions = np.zeros((num_rays, 3), dtype=np.float32)
356
+ directions[:, 2] = 1.0 # Default to +z direction
357
+
358
+ wavelengths = np.zeros(num_rays, dtype=np.float32)
359
+ intensities = np.zeros(num_rays, dtype=np.float32)
360
+ optical_path_lengths = np.zeros(num_rays, dtype=np.float32)
361
+ geometric_path_lengths = np.zeros(num_rays, dtype=np.float32)
362
+ accumulated_time = np.zeros(num_rays, dtype=np.float32)
363
+ generations = np.zeros(num_rays, dtype=np.int32)
364
+ domain_ids = np.zeros(num_rays, dtype=np.int32)
365
+ active = np.zeros(num_rays, dtype=np.bool_)
366
+
367
+ polarization_s = (
368
+ np.zeros(num_rays, dtype=np.float32) if enable_polarization else None
369
+ )
370
+ polarization_p = (
371
+ np.zeros(num_rays, dtype=np.float32) if enable_polarization else None
372
+ )
373
+ polarization_vector = (
374
+ np.zeros((num_rays, 3), dtype=np.float32)
375
+ if enable_polarization_vector
376
+ else None
377
+ )
378
+ phase = np.zeros(num_rays, dtype=np.float32) if enable_phase else None
379
+ optical_depth = (
380
+ np.zeros(num_rays, dtype=np.float32) if enable_optical_depth else None
381
+ )
382
+
383
+ return RayBatch(
384
+ positions=positions,
385
+ directions=directions,
386
+ wavelengths=wavelengths,
387
+ intensities=intensities,
388
+ optical_path_lengths=optical_path_lengths,
389
+ geometric_path_lengths=geometric_path_lengths,
390
+ accumulated_time=accumulated_time,
391
+ generations=generations,
392
+ domain_ids=domain_ids,
393
+ active=active,
394
+ polarization_s=polarization_s,
395
+ polarization_p=polarization_p,
396
+ polarization_vector=polarization_vector,
397
+ phase=phase,
398
+ optical_depth=optical_depth,
399
+ )
400
+
401
+
402
+ def compute_statistics(batch: RayBatch) -> RayStatistics:
403
+ """
404
+ Compute statistical summary of a ray batch.
405
+
406
+ Parameters
407
+ ----------
408
+ batch : RayBatch
409
+ Ray batch to analyze
410
+
411
+ Returns
412
+ -------
413
+ RayStatistics
414
+ Statistical summary
415
+ """
416
+ active_mask = batch.active
417
+ n_active = np.sum(active_mask)
418
+
419
+ if n_active == 0:
420
+ return RayStatistics(
421
+ total_rays=batch.num_rays,
422
+ active_rays=0,
423
+ mean_intensity=0.0,
424
+ total_power=0.0,
425
+ mean_optical_path=0.0,
426
+ mean_generation=0.0,
427
+ max_generation=0,
428
+ )
429
+
430
+ active_intensities = batch.intensities[active_mask]
431
+ active_opl = batch.optical_path_lengths[active_mask]
432
+ active_gen = batch.generations[active_mask]
433
+
434
+ return RayStatistics(
435
+ total_rays=batch.num_rays,
436
+ active_rays=int(n_active),
437
+ mean_intensity=float(np.mean(active_intensities)),
438
+ total_power=float(np.sum(active_intensities)),
439
+ mean_optical_path=float(np.mean(active_opl)),
440
+ mean_generation=float(np.mean(active_gen)),
441
+ max_generation=int(np.max(batch.generations)),
442
+ )
443
+
444
+
445
+ def merge_ray_batches(batches: list) -> RayBatch:
446
+ """
447
+ Merge multiple ray batches into a single batch.
448
+
449
+ Parameters
450
+ ----------
451
+ batches : list of RayBatch
452
+ List of ray batches to merge
453
+
454
+ Returns
455
+ -------
456
+ RayBatch
457
+ Combined ray batch containing all rays from input batches
458
+
459
+ Notes
460
+ -----
461
+ This is useful for combining rays from different sources or for
462
+ collecting rays after ray splitting at interfaces.
463
+ """
464
+ if not batches:
465
+ return create_ray_batch(num_rays=0)
466
+
467
+ # Filter out empty batches
468
+ non_empty = [b for b in batches if b.num_rays > 0]
469
+ if not non_empty:
470
+ return create_ray_batch(num_rays=0)
471
+
472
+ if len(non_empty) == 1:
473
+ return non_empty[0].clone()
474
+
475
+ # Check for polarization, phase, and optical_depth consistency
476
+ has_polarization = all(
477
+ b.polarization_s is not None and b.polarization_p is not None for b in non_empty
478
+ )
479
+ has_polarization_vector = all(b.polarization_vector is not None for b in non_empty)
480
+ has_phase = all(b.phase is not None for b in non_empty)
481
+ has_optical_depth = all(b.optical_depth is not None for b in non_empty)
482
+
483
+ # Concatenate all arrays
484
+ positions = np.vstack([b.positions for b in non_empty])
485
+ directions = np.vstack([b.directions for b in non_empty])
486
+ wavelengths = np.concatenate([b.wavelengths for b in non_empty])
487
+ intensities = np.concatenate([b.intensities for b in non_empty])
488
+ optical_path_lengths = np.concatenate([b.optical_path_lengths for b in non_empty])
489
+ geometric_path_lengths = np.concatenate(
490
+ [b.geometric_path_lengths for b in non_empty]
491
+ )
492
+ accumulated_time = np.concatenate([b.accumulated_time for b in non_empty])
493
+ generations = np.concatenate([b.generations for b in non_empty])
494
+ domain_ids = np.concatenate([b.domain_ids for b in non_empty])
495
+ active = np.concatenate([b.active for b in non_empty])
496
+
497
+ polarization_s = None
498
+ polarization_p = None
499
+ polarization_vector = None
500
+ phase = None
501
+ optical_depth = None
502
+
503
+ if has_polarization:
504
+ polarization_s = np.concatenate([b.polarization_s for b in non_empty])
505
+ polarization_p = np.concatenate([b.polarization_p for b in non_empty])
506
+
507
+ if has_polarization_vector:
508
+ polarization_vector = np.vstack([b.polarization_vector for b in non_empty])
509
+
510
+ if has_phase:
511
+ phase = np.concatenate([b.phase for b in non_empty])
512
+
513
+ if has_optical_depth:
514
+ optical_depth = np.concatenate([b.optical_depth for b in non_empty])
515
+
516
+ return RayBatch(
517
+ positions=positions,
518
+ directions=directions,
519
+ wavelengths=wavelengths,
520
+ intensities=intensities,
521
+ optical_path_lengths=optical_path_lengths,
522
+ geometric_path_lengths=geometric_path_lengths,
523
+ accumulated_time=accumulated_time,
524
+ generations=generations,
525
+ domain_ids=domain_ids,
526
+ active=active,
527
+ polarization_s=polarization_s,
528
+ polarization_p=polarization_p,
529
+ polarization_vector=polarization_vector,
530
+ phase=phase,
531
+ optical_depth=optical_depth,
532
+ )