witwin-maxwell 0.3.0__py3-none-win_amd64.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 (107) hide show
  1. witwin/maxwell/__init__.py +164 -0
  2. witwin/maxwell/adapters/__init__.py +1 -0
  3. witwin/maxwell/adapters/gds.py +203 -0
  4. witwin/maxwell/adapters/tidy3d.py +1669 -0
  5. witwin/maxwell/adjoint_inputs.py +70 -0
  6. witwin/maxwell/compiler/__init__.py +11 -0
  7. witwin/maxwell/compiler/materials.py +1355 -0
  8. witwin/maxwell/compiler/monitors.py +164 -0
  9. witwin/maxwell/compiler/sources.py +222 -0
  10. witwin/maxwell/fdfd/__init__.py +3 -0
  11. witwin/maxwell/fdfd/adjoint/__init__.py +3 -0
  12. witwin/maxwell/fdfd/adjoint/bridge.py +180 -0
  13. witwin/maxwell/fdfd/ams.py +300 -0
  14. witwin/maxwell/fdfd/krylov.py +280 -0
  15. witwin/maxwell/fdfd/plotting.py +110 -0
  16. witwin/maxwell/fdfd/postprocess.py +33 -0
  17. witwin/maxwell/fdfd/solver.py +1057 -0
  18. witwin/maxwell/fdtd/__init__.py +4 -0
  19. witwin/maxwell/fdtd/adjoint/__init__.py +21 -0
  20. witwin/maxwell/fdtd/adjoint/bridge.py +746 -0
  21. witwin/maxwell/fdtd/adjoint/capabilities.py +29 -0
  22. witwin/maxwell/fdtd/adjoint/core.py +3614 -0
  23. witwin/maxwell/fdtd/adjoint/dispatch.py +684 -0
  24. witwin/maxwell/fdtd/adjoint/native.py +2561 -0
  25. witwin/maxwell/fdtd/adjoint/profiler.py +195 -0
  26. witwin/maxwell/fdtd/adjoint/reverse_common.py +207 -0
  27. witwin/maxwell/fdtd/adjoint/seeds.py +524 -0
  28. witwin/maxwell/fdtd/boundary/__init__.py +37 -0
  29. witwin/maxwell/fdtd/boundary/bloch.py +90 -0
  30. witwin/maxwell/fdtd/boundary/common.py +41 -0
  31. witwin/maxwell/fdtd/boundary/cpml.py +527 -0
  32. witwin/maxwell/fdtd/boundary/runtime.py +209 -0
  33. witwin/maxwell/fdtd/checkpoint.py +227 -0
  34. witwin/maxwell/fdtd/coords.py +32 -0
  35. witwin/maxwell/fdtd/cuda/__init__.py +11 -0
  36. witwin/maxwell/fdtd/cuda/backend.py +3532 -0
  37. witwin/maxwell/fdtd/cuda/build.py +292 -0
  38. witwin/maxwell/fdtd/cuda/extension.cpp +2053 -0
  39. witwin/maxwell/fdtd/cuda/kernels/adjoint.cu +5290 -0
  40. witwin/maxwell/fdtd/cuda/kernels/aniso.cu +1704 -0
  41. witwin/maxwell/fdtd/cuda/kernels/boundary.cu +424 -0
  42. witwin/maxwell/fdtd/cuda/kernels/common.cu +74 -0
  43. witwin/maxwell/fdtd/cuda/kernels/common.cuh +82 -0
  44. witwin/maxwell/fdtd/cuda/kernels/dispersive.cu +782 -0
  45. witwin/maxwell/fdtd/cuda/kernels/electric.cu +3613 -0
  46. witwin/maxwell/fdtd/cuda/kernels/magnetic.cu +781 -0
  47. witwin/maxwell/fdtd/cuda/kernels/observers.cu +347 -0
  48. witwin/maxwell/fdtd/cuda/kernels/projection.cu +211 -0
  49. witwin/maxwell/fdtd/cuda/kernels/sources.cu +1482 -0
  50. witwin/maxwell/fdtd/cuda/kernels/spectral.cu +297 -0
  51. witwin/maxwell/fdtd/cuda/launch.h +23 -0
  52. witwin/maxwell/fdtd/cuda/prebuilt/witwin_maxwell_fdtd_cuda.pyd +0 -0
  53. witwin/maxwell/fdtd/cuda/runtime/__init__.py +6 -0
  54. witwin/maxwell/fdtd/cuda/runtime/dispatcher.py +6 -0
  55. witwin/maxwell/fdtd/cuda/runtime/graph.py +33 -0
  56. witwin/maxwell/fdtd/cuda/tensors.h +35 -0
  57. witwin/maxwell/fdtd/dispersion.py +48 -0
  58. witwin/maxwell/fdtd/evaluation.py +290 -0
  59. witwin/maxwell/fdtd/excitation/__init__.py +27 -0
  60. witwin/maxwell/fdtd/excitation/injection.py +1102 -0
  61. witwin/maxwell/fdtd/excitation/modes.py +1675 -0
  62. witwin/maxwell/fdtd/excitation/spatial.py +469 -0
  63. witwin/maxwell/fdtd/excitation/temporal.py +510 -0
  64. witwin/maxwell/fdtd/excitation/tfsf_apply.py +264 -0
  65. witwin/maxwell/fdtd/excitation/tfsf_common.py +421 -0
  66. witwin/maxwell/fdtd/excitation/tfsf_specs.py +490 -0
  67. witwin/maxwell/fdtd/excitation/tfsf_state.py +778 -0
  68. witwin/maxwell/fdtd/io.py +31 -0
  69. witwin/maxwell/fdtd/material_pullback.py +371 -0
  70. witwin/maxwell/fdtd/meshing/__init__.py +3 -0
  71. witwin/maxwell/fdtd/meshing/autogrid.py +335 -0
  72. witwin/maxwell/fdtd/observers.py +1453 -0
  73. witwin/maxwell/fdtd/plotting.py +121 -0
  74. witwin/maxwell/fdtd/postprocess.py +205 -0
  75. witwin/maxwell/fdtd/runtime/__init__.py +119 -0
  76. witwin/maxwell/fdtd/runtime/initialization.py +236 -0
  77. witwin/maxwell/fdtd/runtime/materials.py +1563 -0
  78. witwin/maxwell/fdtd/runtime/module_cache.py +31 -0
  79. witwin/maxwell/fdtd/runtime/spectral.py +581 -0
  80. witwin/maxwell/fdtd/runtime/stepping.py +1987 -0
  81. witwin/maxwell/fdtd/solver.py +502 -0
  82. witwin/maxwell/geometry/__init__.py +5 -0
  83. witwin/maxwell/geometry/polyslab.py +299 -0
  84. witwin/maxwell/materials.py +3 -0
  85. witwin/maxwell/media.py +1467 -0
  86. witwin/maxwell/monitors.py +743 -0
  87. witwin/maxwell/ports.py +113 -0
  88. witwin/maxwell/postprocess/RCS.py +139 -0
  89. witwin/maxwell/postprocess/__init__.py +42 -0
  90. witwin/maxwell/postprocess/diffraction.py +219 -0
  91. witwin/maxwell/postprocess/directivity.py +152 -0
  92. witwin/maxwell/postprocess/emission.py +67 -0
  93. witwin/maxwell/postprocess/modal.py +324 -0
  94. witwin/maxwell/postprocess/nfft.py +266 -0
  95. witwin/maxwell/postprocess/scattering_parameters.py +358 -0
  96. witwin/maxwell/postprocess/stratton_chu.py +1193 -0
  97. witwin/maxwell/result.py +967 -0
  98. witwin/maxwell/scene.py +1338 -0
  99. witwin/maxwell/simulation.py +659 -0
  100. witwin/maxwell/sources.py +917 -0
  101. witwin/maxwell/visualization/__init__.py +28 -0
  102. witwin/maxwell/visualization/interactive.py +484 -0
  103. witwin/maxwell/visualization/plots.py +568 -0
  104. witwin_maxwell-0.3.0.dist-info/METADATA +184 -0
  105. witwin_maxwell-0.3.0.dist-info/RECORD +107 -0
  106. witwin_maxwell-0.3.0.dist-info/WHEEL +4 -0
  107. witwin_maxwell-0.3.0.dist-info/licenses/LICENSE +13 -0
@@ -0,0 +1,67 @@
1
+ """Dipole emission postprocessing: Purcell factor / local density of states.
2
+
3
+ The power a point dipole delivers to the field, ``P = -(1/2) Re(conj(J) . E)``,
4
+ is reported per frequency by a :class:`DipoleEmissionMonitor`. The Purcell factor
5
+ is the ratio of that power in the structured environment to the power the same
6
+ dipole delivers in vacuum. Vacuum normalization (rather than an analytic
7
+ free-space formula) is used because the discrete Yee-grid effective source
8
+ volume, which sets the absolute scale of ``power_delivered``, has no reliable
9
+ closed form; the ratio cancels it exactly when both runs share the grid, the
10
+ source waveform, and the sampling schedule.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import numpy as np
16
+ import torch
17
+
18
+
19
+ def _dipole_payload(source, name: str) -> dict:
20
+ if hasattr(source, "monitor"):
21
+ payload = source.monitor(name)
22
+ else:
23
+ payload = source
24
+ if not isinstance(payload, dict) or payload.get("monitor_type") != "dipole_emission":
25
+ raise ValueError(f"Monitor {name!r} is not a DipoleEmissionMonitor result.")
26
+ power = payload.get("power_delivered")
27
+ if power is None:
28
+ raise ValueError(f"DipoleEmissionMonitor {name!r} has no delivered-power samples.")
29
+ return payload
30
+
31
+
32
+ def _as_real_array(power):
33
+ if isinstance(power, torch.Tensor):
34
+ return power.detach().to(dtype=torch.float64).cpu().numpy()
35
+ return np.asarray(power, dtype=np.float64)
36
+
37
+
38
+ def purcell_factor(structured, vacuum, name: str) -> dict:
39
+ """Return the Purcell factor of a dipole from structured and vacuum runs.
40
+
41
+ ``structured`` and ``vacuum`` may each be a :class:`Result` or an already
42
+ extracted ``DipoleEmissionMonitor`` payload. Both runs must share the grid,
43
+ the dipole waveform, and the frequency sampling so that the discrete source
44
+ normalization cancels in the ratio.
45
+ """
46
+
47
+ structured_payload = _dipole_payload(structured, name)
48
+ vacuum_payload = _dipole_payload(vacuum, name)
49
+
50
+ structured_power = _as_real_array(structured_payload["power_delivered"])
51
+ vacuum_power = _as_real_array(vacuum_payload["power_delivered"])
52
+ if structured_power.shape != vacuum_power.shape:
53
+ raise ValueError(
54
+ "Structured and vacuum dipole runs must share the frequency sampling; "
55
+ f"got shapes {structured_power.shape} and {vacuum_power.shape}."
56
+ )
57
+
58
+ factor = structured_power / vacuum_power
59
+ frequencies = tuple(float(freq) for freq in structured_payload.get("frequencies", ()))
60
+ scalar = factor.ndim == 0 or factor.size == 1
61
+ return {
62
+ "kind": "dipole_emission",
63
+ "purcell_factor": float(factor.reshape(-1)[0]) if scalar else factor,
64
+ "power_delivered": structured_power,
65
+ "power_delivered_vacuum": vacuum_power,
66
+ "frequencies": frequencies,
67
+ }
@@ -0,0 +1,324 @@
1
+ from __future__ import annotations
2
+
3
+ from types import SimpleNamespace
4
+
5
+ import torch
6
+
7
+ from ..compiler.sources import _compile_mode_source
8
+ from ..fdtd.excitation.modes import sample_mode_source_component, solve_mode_source_profile
9
+ from ..scene import prepare_scene
10
+ from ..sources import CW, ModeSource
11
+ from .stratton_chu import (
12
+ _as_1d_coords,
13
+ _resolve_complex_dtype,
14
+ _resolve_real_dtype,
15
+ _resolve_tensor_device,
16
+ _to_complex_tensor,
17
+ _trapz_weights_1d,
18
+ build_plane_points,
19
+ )
20
+
21
+
22
+ _AXIS_TO_INDEX = {"x": 0, "y": 1, "z": 2}
23
+ _INDEX_TO_AXIS = ("x", "y", "z")
24
+ _FIELD_NAMES = ("Ex", "Ey", "Ez", "Hx", "Hy", "Hz")
25
+ _POWER_FLOOR = 1e-30
26
+
27
+
28
+ def _mode_source_from_mode_spec(mode_spec: dict[str, object], *, frequency: float) -> ModeSource:
29
+ polarization_axis = mode_spec.get("polarization_axis")
30
+ if polarization_axis is not None:
31
+ polarization = f"E{str(polarization_axis)}"
32
+ else:
33
+ polarization = tuple(float(component) for component in mode_spec["polarization"])
34
+ return ModeSource(
35
+ position=tuple(float(value) for value in mode_spec["position"]),
36
+ size=tuple(float(value) for value in mode_spec["size"]),
37
+ mode_index=int(mode_spec["mode_index"]),
38
+ direction=str(mode_spec["direction"]),
39
+ polarization=polarization,
40
+ source_time=CW(frequency=float(frequency), amplitude=1.0),
41
+ name=mode_spec.get("name"),
42
+ bend_radius=mode_spec.get("bend_radius"),
43
+ bend_axis=mode_spec.get("bend_axis"),
44
+ )
45
+
46
+
47
+ def _resolve_mode_source(scene, monitor=None, *, mode_source=None, frequency: float) -> ModeSource:
48
+ if mode_source is None and monitor is not None and monitor.get("mode_spec") is not None:
49
+ return _mode_source_from_mode_spec(monitor["mode_spec"], frequency=float(frequency))
50
+
51
+ mode_sources = [source for source in getattr(scene, "sources", ()) if isinstance(source, ModeSource)]
52
+ for port in getattr(scene, "ports", ()):
53
+ port_source = port.to_mode_source()
54
+ if port_source is not None:
55
+ mode_sources.append(port_source)
56
+ if mode_source is None:
57
+ if len(mode_sources) != 1:
58
+ raise ValueError("mode_source must be provided when the scene does not contain exactly one ModeSource.")
59
+ return mode_sources[0]
60
+ if isinstance(mode_source, ModeSource):
61
+ return mode_source
62
+ if isinstance(mode_source, str):
63
+ matches = [source for source in mode_sources if source.name == mode_source]
64
+ if len(matches) != 1:
65
+ raise ValueError(f"ModeSource {mode_source!r} was not uniquely found on result.scene.")
66
+ return matches[0]
67
+ raise TypeError("mode_source must be None, a ModeSource instance, or a ModeSource name.")
68
+
69
+
70
+ def _mode_overlap_context(result):
71
+ solver = getattr(result, "solver", None)
72
+ if solver is not None and hasattr(solver, "_compiled_material_model"):
73
+ return solver
74
+
75
+ scene = result.prepared_scene if hasattr(result, "prepared_scene") else prepare_scene(result.scene)
76
+ device = torch.device(scene.device)
77
+ return SimpleNamespace(
78
+ scene=scene,
79
+ Ex=torch.empty((1,), device=device, dtype=torch.float32),
80
+ c=299792458.0,
81
+ boundary_kind=scene.boundary.kind,
82
+ _compiled_material_model=scene.compile_materials(),
83
+ )
84
+
85
+
86
+ def _monitor_payload(result, monitor_name: str, *, frequency: float | None, freq_index: int | None):
87
+ if hasattr(result, "raw_monitor"):
88
+ monitor = result.raw_monitor(monitor_name, frequency=frequency, freq_index=freq_index)
89
+ else:
90
+ monitor = result.monitor(monitor_name, frequency=frequency, freq_index=freq_index, resolve_modal=False)
91
+ if "axis" not in monitor:
92
+ raise ValueError(f"Monitor {monitor_name!r} is not a plane monitor.")
93
+ return monitor
94
+
95
+
96
+ def _monitor_coords(monitor):
97
+ axis = str(monitor["axis"]).lower()
98
+ tangential_axes = tuple(label for label in "xyz" if label != axis)
99
+ coord_a = monitor.get(tangential_axes[0])
100
+ coord_b = monitor.get(tangential_axes[1])
101
+ if coord_a is None or coord_b is None:
102
+ coords = monitor.get("coords")
103
+ if coords is None or len(coords) != 2:
104
+ raise ValueError("Plane monitor does not expose aligned tangential coordinates.")
105
+ coord_a, coord_b = coords
106
+ return axis, tangential_axes, coord_a, coord_b
107
+
108
+
109
+ def _surface_normal(axis: str, normal_direction: str, *, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
110
+ normal = torch.zeros((3,), device=device, dtype=dtype)
111
+ normal[_AXIS_TO_INDEX[axis]] = 1.0 if str(normal_direction) != "-" else -1.0
112
+ return normal
113
+
114
+
115
+ def _monitor_vector_fields(monitor, shape, *, device: torch.device, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]:
116
+ electric = torch.zeros(shape + (3,), device=device, dtype=dtype)
117
+ magnetic = torch.zeros(shape + (3,), device=device, dtype=dtype)
118
+ for index, axis_label in enumerate(_INDEX_TO_AXIS):
119
+ electric_name = f"E{axis_label}"
120
+ magnetic_name = f"H{axis_label}"
121
+ if electric_name in monitor:
122
+ electric[..., index] = _to_complex_tensor(monitor[electric_name], device=device, dtype=dtype)
123
+ if magnetic_name in monitor:
124
+ magnetic[..., index] = _to_complex_tensor(monitor[magnetic_name], device=device, dtype=dtype)
125
+ return electric, magnetic
126
+
127
+
128
+ def _reference_mode_fields(context, mode_source: ModeSource, monitor, *, frequency: float, direction: str | None):
129
+ axis, tangential_axes, coord_a, coord_b = _monitor_coords(monitor)
130
+ public_source = mode_source
131
+ if axis != public_source.normal_axis:
132
+ raise ValueError(
133
+ f"Monitor axis {axis!r} does not match ModeSource normal axis {public_source.normal_axis!r}."
134
+ )
135
+
136
+ compiled = _compile_mode_source(public_source, default_frequency=float(frequency))
137
+ if direction is not None:
138
+ direction_sign = 1 if str(direction) == "+" else -1
139
+ compiled["direction"] = str(direction)
140
+ compiled["direction_sign"] = int(direction_sign)
141
+ compiled["direction_vector"] = {
142
+ "x": (float(direction_sign), 0.0, 0.0),
143
+ "y": (0.0, float(direction_sign), 0.0),
144
+ "z": (0.0, 0.0, float(direction_sign)),
145
+ }[axis]
146
+ compiled["source_time"] = _compile_mode_source(
147
+ ModeSource(
148
+ position=public_source.position,
149
+ size=public_source.size,
150
+ mode_index=public_source.mode_index,
151
+ direction=compiled["direction"],
152
+ polarization=f"E{public_source.polarization_axis}",
153
+ source_time=CW(frequency=float(frequency), amplitude=1.0),
154
+ name=public_source.name,
155
+ ),
156
+ default_frequency=float(frequency),
157
+ )["source_time"]
158
+
159
+ position = list(compiled["position"])
160
+ position[_AXIS_TO_INDEX[axis]] = float(monitor["position"])
161
+ compiled["position"] = tuple(position)
162
+ mode_data = solve_mode_source_profile(context, compiled)
163
+
164
+ device = _resolve_tensor_device(coord_a, coord_b, mode_data["profile"])
165
+ real_dtype = _resolve_real_dtype(coord_a, coord_b, mode_data["profile"])
166
+ complex_dtype = _resolve_complex_dtype(mode_data["profile"])
167
+ coords_a = _as_1d_coords(coord_a, tangential_axes[0], device=device, dtype=real_dtype)
168
+ coords_b = _as_1d_coords(coord_b, tangential_axes[1], device=device, dtype=real_dtype)
169
+ points = build_plane_points(axis, float(monitor["position"]), coords_a, coords_b).to(
170
+ device=device,
171
+ dtype=real_dtype,
172
+ )
173
+ electric = torch.zeros((coords_a.numel(), coords_b.numel(), 3), device=device, dtype=complex_dtype)
174
+ magnetic = torch.zeros((coords_a.numel(), coords_b.numel(), 3), device=device, dtype=complex_dtype)
175
+ for index, field_name in enumerate(("Ex", "Ey", "Ez")):
176
+ electric[..., index] = sample_mode_source_component(mode_data, points, field_name).to(
177
+ device=device,
178
+ dtype=complex_dtype,
179
+ )
180
+ for index, field_name in enumerate(("Hx", "Hy", "Hz")):
181
+ magnetic[..., index] = sample_mode_source_component(mode_data, points, field_name).to(
182
+ device=device,
183
+ dtype=complex_dtype,
184
+ )
185
+ return coords_a, coords_b, electric, magnetic, mode_data
186
+
187
+
188
+ def _integrated_power(electric: torch.Tensor, magnetic: torch.Tensor, normal: torch.Tensor, weights: torch.Tensor) -> torch.Tensor:
189
+ density = 0.5 * torch.sum(torch.cross(electric, torch.conj(magnetic), dim=-1) * normal, dim=-1)
190
+ return torch.sum(density * weights)
191
+
192
+
193
+ def _compute_mode_overlap_from_payload(
194
+ result,
195
+ monitor_name: str,
196
+ monitor,
197
+ *,
198
+ mode_source: ModeSource | str | None = None,
199
+ direction: str | None = None,
200
+ ) -> dict[str, object]:
201
+ context = _mode_overlap_context(result)
202
+ resolved_frequency = float(monitor.get("frequency", getattr(result, "frequency", None)))
203
+ resolved_mode_source = _resolve_mode_source(
204
+ result.scene,
205
+ monitor,
206
+ mode_source=mode_source,
207
+ frequency=resolved_frequency,
208
+ )
209
+ axis, tangential_axes, coord_a, coord_b = _monitor_coords(monitor)
210
+
211
+ device = _resolve_tensor_device(coord_a, coord_b, *[monitor.get(name) for name in _FIELD_NAMES])
212
+ real_dtype = _resolve_real_dtype(coord_a, coord_b)
213
+ complex_dtype = _resolve_complex_dtype(*[monitor.get(name) for name in _FIELD_NAMES])
214
+ coords_a = _as_1d_coords(coord_a, tangential_axes[0], device=device, dtype=real_dtype)
215
+ coords_b = _as_1d_coords(coord_b, tangential_axes[1], device=device, dtype=real_dtype)
216
+ weights = _trapz_weights_1d(coords_a)[:, None] * _trapz_weights_1d(coords_b)[None, :]
217
+ normal = _surface_normal(
218
+ axis,
219
+ monitor.get("normal_direction", "+"),
220
+ device=device,
221
+ dtype=real_dtype,
222
+ ).to(dtype=complex_dtype)
223
+
224
+ electric_total, magnetic_total = _monitor_vector_fields(
225
+ monitor,
226
+ (coords_a.numel(), coords_b.numel()),
227
+ device=device,
228
+ dtype=complex_dtype,
229
+ )
230
+ coords_ref_a, coords_ref_b, electric_ref, magnetic_ref, mode_data = _reference_mode_fields(
231
+ context,
232
+ resolved_mode_source,
233
+ monitor,
234
+ frequency=resolved_frequency,
235
+ direction=direction,
236
+ )
237
+ coords_ref_a = coords_ref_a.to(device=device, dtype=coords_a.dtype)
238
+ coords_ref_b = coords_ref_b.to(device=device, dtype=coords_b.dtype)
239
+ electric_ref = electric_ref.to(device=device, dtype=complex_dtype)
240
+ magnetic_ref = magnetic_ref.to(device=device, dtype=complex_dtype)
241
+ if coords_ref_a.shape != coords_a.shape or coords_ref_b.shape != coords_b.shape:
242
+ raise ValueError("Reference mode coordinates do not match the monitor coordinates.")
243
+ if not torch.allclose(coords_ref_a, coords_a, atol=1e-6, rtol=0.0) or not torch.allclose(
244
+ coords_ref_b,
245
+ coords_b,
246
+ atol=1e-6,
247
+ rtol=0.0,
248
+ ):
249
+ raise ValueError("Reference mode coordinates do not match the monitor coordinates.")
250
+
251
+ mode_power = _integrated_power(electric_ref, magnetic_ref, normal, weights)
252
+ mode_power_abs = torch.abs(torch.real(mode_power))
253
+ if float(mode_power_abs.item()) <= _POWER_FLOOR:
254
+ raise ValueError("Reference mode power is numerically zero on the supplied monitor plane.")
255
+
256
+ plus_density = torch.sum(
257
+ (
258
+ torch.cross(electric_total, torch.conj(magnetic_ref), dim=-1)
259
+ + torch.cross(torch.conj(electric_ref), magnetic_total, dim=-1)
260
+ )
261
+ * normal,
262
+ dim=-1,
263
+ )
264
+ minus_density = torch.sum(
265
+ (
266
+ torch.cross(electric_total, torch.conj(magnetic_ref), dim=-1)
267
+ - torch.cross(torch.conj(electric_ref), magnetic_total, dim=-1)
268
+ )
269
+ * normal,
270
+ dim=-1,
271
+ )
272
+ amplitude_forward = torch.sum(plus_density * weights) / (4.0 * mode_power)
273
+ amplitude_backward = torch.sum(minus_density * weights) / (4.0 * mode_power)
274
+
275
+ total_power = _integrated_power(electric_total, magnetic_total, normal, weights)
276
+ forward_power = torch.abs(amplitude_forward) ** 2 * mode_power_abs.to(dtype=amplitude_forward.real.dtype)
277
+ backward_power = torch.abs(amplitude_backward) ** 2 * mode_power_abs.to(dtype=amplitude_backward.real.dtype)
278
+ total_power_abs = torch.abs(torch.real(total_power))
279
+ if float(total_power_abs.item()) > _POWER_FLOOR:
280
+ forward_fraction = forward_power / total_power_abs
281
+ backward_fraction = backward_power / total_power_abs
282
+ else:
283
+ forward_fraction = None
284
+ backward_fraction = None
285
+
286
+ return {
287
+ "monitor": monitor_name,
288
+ "frequency": resolved_frequency,
289
+ "axis": axis,
290
+ "position": float(monitor["position"]),
291
+ "direction": direction or resolved_mode_source.direction,
292
+ "mode_index": int(resolved_mode_source.mode_index),
293
+ "polarization_axis": resolved_mode_source.polarization_axis,
294
+ "effective_index": float(mode_data["effective_index"]),
295
+ "beta": float(mode_data["beta"]),
296
+ "mode_power": torch.real(mode_power),
297
+ "total_power": torch.real(total_power),
298
+ "amplitude_forward": amplitude_forward,
299
+ "amplitude_backward": amplitude_backward,
300
+ "power_forward": forward_power,
301
+ "power_backward": backward_power,
302
+ "power_fraction_forward": forward_fraction,
303
+ "power_fraction_backward": backward_fraction,
304
+ "coords": (coords_a, coords_b),
305
+ }
306
+
307
+
308
+ def compute_mode_overlap(
309
+ result,
310
+ monitor_name: str,
311
+ *,
312
+ mode_source: ModeSource | str | None = None,
313
+ direction: str | None = None,
314
+ frequency: float | None = None,
315
+ freq_index: int | None = None,
316
+ ) -> dict[str, object]:
317
+ monitor = _monitor_payload(result, monitor_name, frequency=frequency, freq_index=freq_index)
318
+ return _compute_mode_overlap_from_payload(
319
+ result,
320
+ monitor_name,
321
+ monitor,
322
+ mode_source=mode_source,
323
+ direction=direction,
324
+ )
@@ -0,0 +1,266 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+
5
+ import torch
6
+
7
+ from .stratton_chu import (
8
+ EquivalentCurrentsSurface,
9
+ PlanarEquivalentCurrents,
10
+ SurfaceEquivalentCurrents,
11
+ _as_1d_coords,
12
+ _background_wavenumber_and_impedance,
13
+ _normalize_currents_collection,
14
+ _resolve_complex_dtype,
15
+ _resolve_currents_background,
16
+ _resolve_device,
17
+ _resolve_physical_constants,
18
+ _resolve_real_dtype,
19
+ _resolve_tensor_device,
20
+ _to_real_tensor,
21
+ )
22
+
23
+
24
+ def _normalize_directions(directions) -> torch.Tensor:
25
+ device = _resolve_tensor_device(directions)
26
+ dtype = _resolve_real_dtype(directions)
27
+ vectors = _to_real_tensor(directions, device=device, dtype=dtype)
28
+ if vectors.ndim == 1:
29
+ if vectors.shape[0] != 3:
30
+ raise ValueError("directions must have shape (3,) or (N, 3).")
31
+ vectors = vectors[None, :]
32
+ if vectors.ndim != 2 or vectors.shape[1] != 3:
33
+ raise ValueError("directions must have shape (N, 3).")
34
+
35
+ norms = torch.linalg.norm(vectors, dim=1, keepdim=True)
36
+ if torch.any(norms <= 0.0):
37
+ raise ValueError("directions must be non-zero vectors.")
38
+ return vectors / norms
39
+
40
+
41
+ def _broadcast_radius(radius, shape: tuple[int, ...], *, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
42
+ radii = _to_real_tensor(radius, device=device, dtype=dtype)
43
+ if torch.any(radii <= 0.0):
44
+ raise ValueError("radius must be positive.")
45
+ return torch.broadcast_to(radii, shape).clone()
46
+
47
+
48
+ class NearFieldFarFieldTransformer:
49
+ def __init__(
50
+ self,
51
+ currents: PlanarEquivalentCurrents | EquivalentCurrentsSurface | SurfaceEquivalentCurrents,
52
+ *,
53
+ solver=None,
54
+ c: float | None = None,
55
+ eps0: float | None = None,
56
+ mu0: float | None = None,
57
+ background_eps_r: complex | float | None = None,
58
+ background_mu_r: complex | float | None = None,
59
+ device: str | torch.device | None = None,
60
+ ):
61
+ self.currents = currents
62
+ self._surfaces = _normalize_currents_collection(currents)
63
+ self.solver = solver
64
+ self.device = _resolve_device(device)
65
+ self.c, self.eps0, self.mu0 = _resolve_physical_constants(
66
+ solver=solver,
67
+ c=c,
68
+ eps0=eps0,
69
+ mu0=mu0,
70
+ )
71
+ self.background_eps_r, self.background_mu_r = _resolve_currents_background(
72
+ self._surfaces, background_eps_r, background_mu_r
73
+ )
74
+ self.frequency = float(self._surfaces[0].frequency)
75
+ self.coord_dtype = self._surfaces[0].coord_dtype
76
+ self.field_dtype = _resolve_complex_dtype(*(surface.J for surface in self._surfaces), *(surface.M for surface in self._surfaces))
77
+ self.omega = 2.0 * math.pi * self.frequency
78
+ self.eta0 = math.sqrt(self.mu0 / self.eps0)
79
+ # Near-to-far-field radiation uses the homogeneous exterior background's
80
+ # wavenumber and intrinsic impedance (vacuum when the box sits in free
81
+ # space, the sampled dielectric otherwise).
82
+ self.k, self.eta = _background_wavenumber_and_impedance(
83
+ self.background_eps_r,
84
+ self.background_mu_r,
85
+ omega=self.omega,
86
+ c=self.c,
87
+ eta_vacuum=self.eta0,
88
+ )
89
+
90
+ source_points = []
91
+ weighted_j = []
92
+ weighted_m = []
93
+ for surface in self._surfaces:
94
+ points, surface_j, surface_m = surface.quadrature()
95
+ source_points.append(points.reshape(-1, 3))
96
+ weighted_j.append(surface_j.reshape(-1, 3))
97
+ weighted_m.append(surface_m.reshape(-1, 3))
98
+
99
+ self._src_points = torch.cat(source_points, dim=0).to(device=self.device, dtype=self.coord_dtype)
100
+ self._J_w = torch.cat(weighted_j, dim=0).to(device=self.device, dtype=self.field_dtype)
101
+ self._M_w = torch.cat(weighted_m, dim=0).to(device=self.device, dtype=self.field_dtype)
102
+
103
+ def _transform_batch(
104
+ self,
105
+ directions: torch.Tensor,
106
+ radius: torch.Tensor,
107
+ ) -> tuple[torch.Tensor, torch.Tensor]:
108
+ direction_real = directions.to(device=self.device, dtype=self.coord_dtype)
109
+ radius_real = radius.to(device=self.device, dtype=self.coord_dtype)
110
+ direction_complex = direction_real.to(dtype=self.field_dtype)
111
+ phase = torch.exp(
112
+ -1j * self.k * torch.matmul(direction_real, self._src_points.transpose(0, 1)).to(dtype=self.field_dtype)
113
+ )
114
+ n_vector = torch.matmul(phase, self._J_w)
115
+ l_vector = torch.matmul(phase, self._M_w)
116
+
117
+ cross_s_n = torch.cross(direction_complex, n_vector, dim=-1)
118
+ cross_s_l = torch.cross(direction_complex, l_vector, dim=-1)
119
+ radius_complex = radius_real.to(dtype=self.field_dtype)
120
+ prefactor = (
121
+ -1j
122
+ * self.k
123
+ * torch.exp(1j * self.k * radius_complex)
124
+ / (4.0 * math.pi * radius_complex)
125
+ )[:, None]
126
+
127
+ e_field = prefactor * (
128
+ self.eta * torch.cross(direction_complex, cross_s_n, dim=-1)
129
+ + cross_s_l
130
+ )
131
+ h_field = prefactor * (
132
+ (1.0 / self.eta) * torch.cross(direction_complex, cross_s_l, dim=-1)
133
+ - cross_s_n
134
+ )
135
+ return e_field, h_field
136
+
137
+ def transform_directions(
138
+ self,
139
+ directions,
140
+ *,
141
+ radius: float | torch.Tensor = 1.0,
142
+ batch_size: int = 1024,
143
+ ) -> dict[str, torch.Tensor | float]:
144
+ direction_tensor = _normalize_directions(directions).to(device=self.device, dtype=self.coord_dtype)
145
+ radius_tensor = _broadcast_radius(
146
+ radius,
147
+ direction_tensor.shape[:-1],
148
+ device=self.device,
149
+ dtype=self.coord_dtype,
150
+ ).reshape(-1)
151
+ if batch_size <= 0:
152
+ raise ValueError("batch_size must be positive.")
153
+
154
+ e_batches = []
155
+ h_batches = []
156
+ for start in range(0, direction_tensor.shape[0], batch_size):
157
+ stop = min(start + batch_size, direction_tensor.shape[0])
158
+ e_batch, h_batch = self._transform_batch(
159
+ direction_tensor[start:stop],
160
+ radius_tensor[start:stop],
161
+ )
162
+ e_batches.append(e_batch)
163
+ h_batches.append(h_batch)
164
+
165
+ e_field = torch.cat(e_batches, dim=0)
166
+ h_field = torch.cat(h_batches, dim=0)
167
+ poynting = 0.5 * torch.real(torch.cross(e_field, torch.conj(h_field), dim=-1))
168
+ power_density = torch.sum(poynting * direction_tensor, dim=-1)
169
+
170
+ return {
171
+ "directions": direction_tensor,
172
+ "radius": radius_tensor,
173
+ "frequency": self.frequency,
174
+ "E": e_field,
175
+ "H": h_field,
176
+ "Ex": e_field[:, 0],
177
+ "Ey": e_field[:, 1],
178
+ "Ez": e_field[:, 2],
179
+ "Hx": h_field[:, 0],
180
+ "Hy": h_field[:, 1],
181
+ "Hz": h_field[:, 2],
182
+ "power_density": power_density,
183
+ }
184
+
185
+ def transform(
186
+ self,
187
+ theta,
188
+ phi,
189
+ *,
190
+ radius: float | torch.Tensor = 1.0,
191
+ batch_size: int = 1024,
192
+ ) -> dict[str, torch.Tensor | float]:
193
+ device = _resolve_tensor_device(theta, phi)
194
+ dtype = _resolve_real_dtype(theta, phi)
195
+ theta_tensor = _to_real_tensor(theta, device=device, dtype=dtype)
196
+ phi_tensor = _to_real_tensor(phi, device=device, dtype=dtype)
197
+ theta_grid, phi_grid = torch.broadcast_tensors(theta_tensor, phi_tensor)
198
+ direction_tensor = torch.stack(
199
+ (
200
+ torch.sin(theta_grid) * torch.cos(phi_grid),
201
+ torch.sin(theta_grid) * torch.sin(phi_grid),
202
+ torch.cos(theta_grid),
203
+ ),
204
+ dim=-1,
205
+ )
206
+ radius_tensor = _broadcast_radius(
207
+ radius,
208
+ theta_grid.shape,
209
+ device=device,
210
+ dtype=dtype,
211
+ )
212
+ transformed = self.transform_directions(
213
+ direction_tensor.reshape(-1, 3),
214
+ radius=radius_tensor.reshape(-1),
215
+ batch_size=batch_size,
216
+ )
217
+
218
+ shape = theta_grid.shape
219
+ directions = transformed["directions"].reshape(shape + (3,))
220
+ e_field = transformed["E"].reshape(shape + (3,))
221
+ h_field = transformed["H"].reshape(shape + (3,))
222
+ theta_on_device = theta_grid.to(device=self.device, dtype=self.coord_dtype)
223
+ phi_on_device = phi_grid.to(device=self.device, dtype=self.coord_dtype)
224
+
225
+ e_theta_hat = torch.stack(
226
+ (
227
+ torch.cos(theta_on_device) * torch.cos(phi_on_device),
228
+ torch.cos(theta_on_device) * torch.sin(phi_on_device),
229
+ -torch.sin(theta_on_device),
230
+ ),
231
+ dim=-1,
232
+ ).to(dtype=self.field_dtype)
233
+ e_phi_hat = torch.stack(
234
+ (
235
+ -torch.sin(phi_on_device),
236
+ torch.cos(phi_on_device),
237
+ torch.zeros_like(phi_on_device),
238
+ ),
239
+ dim=-1,
240
+ ).to(dtype=self.field_dtype)
241
+
242
+ e_theta = torch.sum(e_field * e_theta_hat, dim=-1)
243
+ e_phi = torch.sum(e_field * e_phi_hat, dim=-1)
244
+ h_theta = torch.sum(h_field * e_theta_hat, dim=-1)
245
+ h_phi = torch.sum(h_field * e_phi_hat, dim=-1)
246
+
247
+ return {
248
+ "theta": theta_on_device,
249
+ "phi": phi_on_device,
250
+ "radius": radius_tensor.to(device=self.device, dtype=self.coord_dtype),
251
+ "directions": directions,
252
+ "frequency": self.frequency,
253
+ "E": e_field,
254
+ "H": h_field,
255
+ "Ex": e_field[..., 0],
256
+ "Ey": e_field[..., 1],
257
+ "Ez": e_field[..., 2],
258
+ "Hx": h_field[..., 0],
259
+ "Hy": h_field[..., 1],
260
+ "Hz": h_field[..., 2],
261
+ "E_theta": e_theta,
262
+ "E_phi": e_phi,
263
+ "H_theta": h_theta,
264
+ "H_phi": h_phi,
265
+ "power_density": transformed["power_density"].reshape(shape),
266
+ }