jcmsuite 7.4.2__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.
Potentially problematic release.
This version of jcmsuite might be problematic. Click here for more details.
- jcmsuite/__init__.py +22 -0
- jcmsuite/_build_info.py +4 -0
- jcmsuite/context/__init__.py +44 -0
- jcmsuite/context/interface_metadata.py +158 -0
- jcmsuite/context/models.py +213 -0
- jcmsuite/context/scope.py +210 -0
- jcmsuite/context/solver_context.py +569 -0
- jcmsuite/context/subprocess_tools.py +172 -0
- jcmsuite/contract.py +47 -0
- jcmsuite/daemon/__init__.py +19 -0
- jcmsuite/daemon/handler.py +925 -0
- jcmsuite/daemon/internal/__init__.py +4 -0
- jcmsuite/daemon/internal/bundle_protocol.py +64 -0
- jcmsuite/daemon/internal/handler_helpers.py +368 -0
- jcmsuite/daemon/internal/handler_resource_jobs.py +227 -0
- jcmsuite/daemon/internal/handler_wait.py +564 -0
- jcmsuite/daemon/models.py +349 -0
- jcmsuite/daemon/namespaces.py +250 -0
- jcmsuite/daemon/protocol.py +801 -0
- jcmsuite/daemon/resources.py +407 -0
- jcmsuite/daemon/scope.py +53 -0
- jcmsuite/daemon/transport.py +223 -0
- jcmsuite/editing/__init__.py +10 -0
- jcmsuite/editing/editor.py +274 -0
- jcmsuite/exceptions/__init__.py +32 -0
- jcmsuite/exceptions/errors.py +173 -0
- jcmsuite/geo/__init__.py +10 -0
- jcmsuite/geo/mesh.py +302 -0
- jcmsuite/info/__init__.py +10 -0
- jcmsuite/info/runtime_info.py +45 -0
- jcmsuite/internal/__init__.py +2 -0
- jcmsuite/internal/diagnostics.py +74 -0
- jcmsuite/internal/progress.py +80 -0
- jcmsuite/loaders/__init__.py +18 -0
- jcmsuite/loaders/blob_header.py +315 -0
- jcmsuite/loaders/cartesian_field_reader.py +249 -0
- jcmsuite/loaders/cartesian_fields.py +324 -0
- jcmsuite/loaders/nested_mapping.py +69 -0
- jcmsuite/loaders/powerflux.py +136 -0
- jcmsuite/loaders/table.py +637 -0
- jcmsuite/logging/__init__.py +22 -0
- jcmsuite/logging/runtime.py +210 -0
- jcmsuite/results/__init__.py +126 -0
- jcmsuite/results/artifacts.py +806 -0
- jcmsuite/results/discovery.py +82 -0
- jcmsuite/results/field_exports.py +1062 -0
- jcmsuite/results/field_payloads.py +453 -0
- jcmsuite/results/internal/__init__.py +4 -0
- jcmsuite/results/internal/export/__init__.py +4 -0
- jcmsuite/results/internal/export/common.py +56 -0
- jcmsuite/results/internal/export/pandas/__init__.py +4 -0
- jcmsuite/results/internal/export/pandas/common.py +165 -0
- jcmsuite/results/internal/export/pandas/payload.py +480 -0
- jcmsuite/results/internal/export/pandas/rows.py +484 -0
- jcmsuite/results/internal/export/preview.py +178 -0
- jcmsuite/results/internal/export/xarray/__init__.py +4 -0
- jcmsuite/results/internal/export/xarray/export.py +688 -0
- jcmsuite/results/internal/export/xarray/grouped.py +608 -0
- jcmsuite/results/internal/export/xarray/headers.py +290 -0
- jcmsuite/results/internal/export/xarray/runtime.py +99 -0
- jcmsuite/results/internal/export/xarray/shared.py +246 -0
- jcmsuite/results/internal/export/xarray/tabular.py +304 -0
- jcmsuite/results/internal/export/xarray/types.py +28 -0
- jcmsuite/results/internal/models/__init__.py +4 -0
- jcmsuite/results/internal/models/batch.py +1081 -0
- jcmsuite/results/internal/models/batch_postprocess.py +1728 -0
- jcmsuite/results/internal/models/bundle.py +343 -0
- jcmsuite/results/internal/models/core.py +556 -0
- jcmsuite/results/internal/models/submission.py +1157 -0
- jcmsuite/results/internal/resultbag/__init__.py +4 -0
- jcmsuite/results/internal/resultbag/access.py +489 -0
- jcmsuite/results/internal/resultbag/iteration.py +199 -0
- jcmsuite/results/internal/resultbag/query.py +226 -0
- jcmsuite/results/internal/resultbag/raw.py +407 -0
- jcmsuite/results/internal/resultbag/source_files.py +142 -0
- jcmsuite/results/internal/resultbag/store.py +881 -0
- jcmsuite/results/internal/resultbag/utils.py +258 -0
- jcmsuite/results/models.py +76 -0
- jcmsuite/results/opening.py +55 -0
- jcmsuite/results/pandas_export.py +325 -0
- jcmsuite/results/payloads.py +478 -0
- jcmsuite/results/postprocess.py +97 -0
- jcmsuite/results/postprocess_payloads.py +757 -0
- jcmsuite/results/postprocess_record.py +418 -0
- jcmsuite/results/resultbag.py +279 -0
- jcmsuite/results/resultbag_management.py +433 -0
- jcmsuite/results/structured_derivatives.py +387 -0
- jcmsuite/solve/__init__.py +10 -0
- jcmsuite/solve/daemon_bundle_staging.py +100 -0
- jcmsuite/solve/daemon_bundle_wait.py +89 -0
- jcmsuite/solve/orchestration.py +1576 -0
- jcmsuite/solve/orchestration_execution.py +180 -0
- jcmsuite/solve/orchestration_routing.py +128 -0
- jcmsuite/solve/orchestration_support.py +323 -0
- jcmsuite/solve/path_resolution.py +98 -0
- jcmsuite/solve/progress.py +20 -0
- jcmsuite/solve/solver.py +709 -0
- jcmsuite/solve/staging.py +264 -0
- jcmsuite/solve/types.py +25 -0
- jcmsuite/solve/working_dirs.py +227 -0
- jcmsuite/templates/__init__.py +11 -0
- jcmsuite/templates/converter.py +71 -0
- jcmsuite/templates/formatting.py +335 -0
- jcmsuite/templates/formatting_cli.py +47 -0
- jcmsuite/templates/rendering.py +666 -0
- jcmsuite/torch/__init__.py +25 -0
- jcmsuite/torch/autograd.py +488 -0
- jcmsuite/torch/coordinate_policy.py +82 -0
- jcmsuite/torch/core.py +312 -0
- jcmsuite/torch/results/__init__.py +51 -0
- jcmsuite/torch/types.py +84 -0
- jcmsuite/torch/validation.py +208 -0
- jcmsuite/torch/wrappers.py +4332 -0
- jcmsuite/view/__init__.py +10 -0
- jcmsuite/view/viewer.py +122 -0
- jcmsuite-7.4.2.dist-info/METADATA +180 -0
- jcmsuite-7.4.2.dist-info/RECORD +119 -0
- jcmsuite-7.4.2.dist-info/WHEEL +4 -0
- jcmsuite-7.4.2.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2001-2026 JCMwave GmbH
|
|
3
|
+
|
|
4
|
+
"""Cartesian fieldbag loader."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import TYPE_CHECKING, Literal, cast
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from ..exceptions import InvalidConfigurationError
|
|
15
|
+
from .blob_header import BlobHeaderReader
|
|
16
|
+
from .cartesian_field_reader import (
|
|
17
|
+
_coerce_int,
|
|
18
|
+
_FieldMode,
|
|
19
|
+
_FieldPayloadReader,
|
|
20
|
+
attach_derivative_branches,
|
|
21
|
+
field_block_count,
|
|
22
|
+
read_parameter_derivatives,
|
|
23
|
+
)
|
|
24
|
+
from .nested_mapping import nested_get, nested_set
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from ..results import FieldExportPayload
|
|
28
|
+
|
|
29
|
+
CartesianFieldFormat = Literal["squeeze", "full"]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def load_cartesian_fields(
|
|
33
|
+
file_name: str | Path,
|
|
34
|
+
*,
|
|
35
|
+
format: CartesianFieldFormat = "squeeze",
|
|
36
|
+
) -> "FieldExportPayload":
|
|
37
|
+
"""Load field values on a Cartesian grid.
|
|
38
|
+
|
|
39
|
+
Parameters
|
|
40
|
+
----------
|
|
41
|
+
file_name : str | Path
|
|
42
|
+
Path to a Cartesian fieldbag `.jcm` file.
|
|
43
|
+
format : {"squeeze", "full"}, optional
|
|
44
|
+
Shape of the returned coordinate arrays and field values. `"squeeze"`
|
|
45
|
+
removes dimensions of length 1. `"full"` keeps all dimensions. The
|
|
46
|
+
method supports text and binary fieldbag files.
|
|
47
|
+
|
|
48
|
+
Returns
|
|
49
|
+
-------
|
|
50
|
+
FieldExportPayload
|
|
51
|
+
Coordinates, field values, available derivatives, and file
|
|
52
|
+
information.
|
|
53
|
+
|
|
54
|
+
Raises
|
|
55
|
+
------
|
|
56
|
+
InvalidConfigurationError
|
|
57
|
+
If `file_name` is not a file or `format` is not supported.
|
|
58
|
+
RuntimeError
|
|
59
|
+
If the fieldbag file is damaged or uses an unsupported storage format.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
file_path: Path = Path(file_name).expanduser().resolve()
|
|
63
|
+
if not file_path.is_file():
|
|
64
|
+
raise InvalidConfigurationError("file_name -> file path expected.")
|
|
65
|
+
if format not in {"squeeze", "full"}:
|
|
66
|
+
raise InvalidConfigurationError("Invalid format.")
|
|
67
|
+
|
|
68
|
+
with open(file_path, "rb") as stream:
|
|
69
|
+
header: dict[str | int, object] = BlobHeaderReader(
|
|
70
|
+
stream,
|
|
71
|
+
"CartesianFieldBag",
|
|
72
|
+
).read_header()
|
|
73
|
+
|
|
74
|
+
n_fields: int = _coerce_int(header.get("NFields"), key_name="NFields")
|
|
75
|
+
n_subfields: int = 0
|
|
76
|
+
while True:
|
|
77
|
+
tensor_vector_object: object | None = header.get("TensorQuantityVector")
|
|
78
|
+
if not isinstance(tensor_vector_object, Mapping):
|
|
79
|
+
break
|
|
80
|
+
if n_subfields not in tensor_vector_object:
|
|
81
|
+
break
|
|
82
|
+
n_subfields += 1
|
|
83
|
+
|
|
84
|
+
n_components: list[int] = []
|
|
85
|
+
subfield_index: int
|
|
86
|
+
for subfield_index in range(n_subfields):
|
|
87
|
+
tensor_vector = cast(
|
|
88
|
+
Mapping[str | int, object], header["TensorQuantityVector"]
|
|
89
|
+
)
|
|
90
|
+
component_header_object: object = tensor_vector[subfield_index]
|
|
91
|
+
if not isinstance(component_header_object, Mapping):
|
|
92
|
+
raise RuntimeError("Corrupted file.")
|
|
93
|
+
n_components.append(
|
|
94
|
+
_coerce_int(
|
|
95
|
+
component_header_object.get("NComponents"),
|
|
96
|
+
key_name=f"TensorQuantityVector[{subfield_index}].NComponents",
|
|
97
|
+
)
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
grid_object: object | None = header.get("Grid")
|
|
101
|
+
if not isinstance(grid_object, Mapping):
|
|
102
|
+
raise RuntimeError("Corrupted file.")
|
|
103
|
+
|
|
104
|
+
space_dim: int = _coerce_int(
|
|
105
|
+
grid_object.get("SpaceDim"), key_name="Grid.SpaceDim"
|
|
106
|
+
)
|
|
107
|
+
lattice_object: object | None = grid_object.get("NPoints")
|
|
108
|
+
if not isinstance(lattice_object, np.ndarray):
|
|
109
|
+
raise RuntimeError("Corrupted file.")
|
|
110
|
+
lattice: np.ndarray = _normalize_lattice(
|
|
111
|
+
lattice_object,
|
|
112
|
+
space_dim=space_dim,
|
|
113
|
+
)
|
|
114
|
+
lattice_values: tuple[int, ...] = tuple(
|
|
115
|
+
int(axis_length) for axis_length in lattice
|
|
116
|
+
)
|
|
117
|
+
if len(lattice_values) != 3:
|
|
118
|
+
raise RuntimeError("Corrupted file.")
|
|
119
|
+
lattice_shape: tuple[int, int, int] = (
|
|
120
|
+
lattice_values[0],
|
|
121
|
+
lattice_values[1],
|
|
122
|
+
lattice_values[2],
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
n_points: int = int(np.prod(lattice_shape))
|
|
126
|
+
n_cells: int = int(
|
|
127
|
+
np.prod([max(axis_length - 1, 1) for axis_length in lattice_shape])
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
mode_raw: object | None = header.get("__MODE__")
|
|
131
|
+
if not isinstance(mode_raw, str):
|
|
132
|
+
raise RuntimeError("Corrupted file.")
|
|
133
|
+
mode: str = mode_raw
|
|
134
|
+
if mode == "BINARY0":
|
|
135
|
+
zero_marker: bytes = stream.read(1)
|
|
136
|
+
if zero_marker != b"0":
|
|
137
|
+
raise RuntimeError("Corrupted file.")
|
|
138
|
+
mode = "BINARY"
|
|
139
|
+
if mode not in {"BINARY", "TEXT"}:
|
|
140
|
+
raise RuntimeError("File not in binary format.")
|
|
141
|
+
|
|
142
|
+
derivative_spec = read_parameter_derivatives(header)
|
|
143
|
+
n_total_fields: int = field_block_count(
|
|
144
|
+
base_field_count=n_fields,
|
|
145
|
+
derivative_spec=derivative_spec,
|
|
146
|
+
)
|
|
147
|
+
reader: _FieldPayloadReader = _FieldPayloadReader.from_stream(
|
|
148
|
+
stream=stream,
|
|
149
|
+
mode=cast(_FieldMode, mode),
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
fieldbag: dict[str, object] = {}
|
|
153
|
+
points: list[np.ndarray] = [
|
|
154
|
+
np.arange(0, 0.1, 0.1),
|
|
155
|
+
np.arange(0, 0.1, 0.1),
|
|
156
|
+
np.arange(0, 0.1, 0.1),
|
|
157
|
+
]
|
|
158
|
+
field_list: list[np.ndarray] = []
|
|
159
|
+
fieldbag["field"] = field_list
|
|
160
|
+
|
|
161
|
+
try:
|
|
162
|
+
axis_index: int
|
|
163
|
+
for axis_index in range(space_dim):
|
|
164
|
+
points[axis_index] = reader.read_numeric_array(
|
|
165
|
+
dtype=np.float64,
|
|
166
|
+
count=lattice_shape[axis_index],
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
contains_domain_ids: bool = False
|
|
170
|
+
try:
|
|
171
|
+
contains_domain_ids = (
|
|
172
|
+
cast(str, nested_get(header, ["Grid", "ContainsDomainIds"]))
|
|
173
|
+
== "yes"
|
|
174
|
+
)
|
|
175
|
+
except KeyError:
|
|
176
|
+
contains_domain_ids = False
|
|
177
|
+
try:
|
|
178
|
+
contains_domain_ids = (
|
|
179
|
+
cast(str, nested_get(header, ["Grid", "ContainsMaterialIds"]))
|
|
180
|
+
== "yes"
|
|
181
|
+
)
|
|
182
|
+
except KeyError:
|
|
183
|
+
pass
|
|
184
|
+
|
|
185
|
+
if contains_domain_ids:
|
|
186
|
+
nested_set(
|
|
187
|
+
cast(dict[str | int, object], fieldbag),
|
|
188
|
+
["grid", "domainIds"],
|
|
189
|
+
reader.read_numeric_array(
|
|
190
|
+
dtype=np.int32,
|
|
191
|
+
count=n_cells,
|
|
192
|
+
),
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
n_comp: int = n_components[0]
|
|
196
|
+
field_index: int
|
|
197
|
+
for field_index in range(n_total_fields):
|
|
198
|
+
values: np.ndarray = reader.read_complex_array(
|
|
199
|
+
component_count=n_comp,
|
|
200
|
+
point_count=n_points,
|
|
201
|
+
)
|
|
202
|
+
values = values.reshape((n_points, n_comp), copy=False)
|
|
203
|
+
field_list.append(values)
|
|
204
|
+
except Exception as error:
|
|
205
|
+
raise RuntimeError("Corrupted file.") from error
|
|
206
|
+
|
|
207
|
+
tensor_vector = cast(Mapping[str | int, object], header["TensorQuantityVector"])
|
|
208
|
+
first_tensor = cast(Mapping[str | int, object], tensor_vector[0])
|
|
209
|
+
polarization: str = cast(str, first_tensor["Polarization"])
|
|
210
|
+
quantity_type: str = cast(str, first_tensor["Type"])
|
|
211
|
+
|
|
212
|
+
if polarization != "xyz" and "Strength" in quantity_type:
|
|
213
|
+
indices: list[int] = []
|
|
214
|
+
axis_index = 0
|
|
215
|
+
for axis_index in range(3):
|
|
216
|
+
if polarization.count("xyz"[axis_index]):
|
|
217
|
+
indices.append(axis_index)
|
|
218
|
+
field_index = 0
|
|
219
|
+
for field_index in range(n_total_fields):
|
|
220
|
+
polarization_data: np.ndarray = field_list[field_index]
|
|
221
|
+
field_list[field_index] = np.ndarray(
|
|
222
|
+
(polarization_data.shape[0], 3),
|
|
223
|
+
dtype="complex128",
|
|
224
|
+
)
|
|
225
|
+
field_list[field_index].fill(0.0)
|
|
226
|
+
field_list[field_index][:, indices] = polarization_data
|
|
227
|
+
n_comp = 3
|
|
228
|
+
else:
|
|
229
|
+
n_comp = n_components[0]
|
|
230
|
+
|
|
231
|
+
x_grid: np.ndarray = np.ndarray(lattice_shape)
|
|
232
|
+
y_grid: np.ndarray = np.ndarray(lattice_shape)
|
|
233
|
+
z_grid: np.ndarray = np.ndarray(lattice_shape)
|
|
234
|
+
|
|
235
|
+
y_index: int
|
|
236
|
+
z_index: int
|
|
237
|
+
for y_index in range(lattice_shape[1]):
|
|
238
|
+
for z_index in range(lattice_shape[2]):
|
|
239
|
+
x_grid[:, y_index, z_index] = points[0]
|
|
240
|
+
|
|
241
|
+
x_index: int
|
|
242
|
+
for x_index in range(lattice_shape[0]):
|
|
243
|
+
for z_index in range(lattice_shape[2]):
|
|
244
|
+
y_grid[x_index, :, z_index] = points[1]
|
|
245
|
+
|
|
246
|
+
for x_index in range(lattice_shape[0]):
|
|
247
|
+
for y_index in range(lattice_shape[1]):
|
|
248
|
+
z_grid[x_index, y_index, :] = points[2]
|
|
249
|
+
|
|
250
|
+
if format == "squeeze":
|
|
251
|
+
x_grid = np.squeeze(x_grid)
|
|
252
|
+
y_grid = np.squeeze(y_grid)
|
|
253
|
+
z_grid = np.squeeze(z_grid)
|
|
254
|
+
|
|
255
|
+
if header.get("CoordinateSystem") == "Polar":
|
|
256
|
+
fieldbag["Theta"] = x_grid
|
|
257
|
+
fieldbag["Phi"] = y_grid
|
|
258
|
+
fieldbag["R"] = z_grid
|
|
259
|
+
else:
|
|
260
|
+
fieldbag["X"] = x_grid
|
|
261
|
+
fieldbag["Y"] = y_grid
|
|
262
|
+
fieldbag["Z"] = z_grid
|
|
263
|
+
|
|
264
|
+
shape: list[int] = list(x_grid.shape)
|
|
265
|
+
shape.append(n_comp)
|
|
266
|
+
field_index = 0
|
|
267
|
+
for field_index in range(n_fields):
|
|
268
|
+
field_list[field_index] = field_list[field_index].reshape(shape, order="F")
|
|
269
|
+
|
|
270
|
+
try:
|
|
271
|
+
fieldbag["header"] = {
|
|
272
|
+
"Origin": cast(Mapping[str | int, object], header["Grid"])["Origin"],
|
|
273
|
+
"Rotation": np.eye(3),
|
|
274
|
+
"QuantityType": quantity_type,
|
|
275
|
+
}
|
|
276
|
+
rotation_direction: str
|
|
277
|
+
for direction_index, rotation_direction in enumerate(["X", "Y", "Z"]):
|
|
278
|
+
rotation_column = cast(
|
|
279
|
+
Mapping[str | int, object],
|
|
280
|
+
header["Grid"],
|
|
281
|
+
)[f"Rotation{rotation_direction}"]
|
|
282
|
+
rotation_matrix: np.ndarray = cast(
|
|
283
|
+
np.ndarray,
|
|
284
|
+
cast(dict[str, object], fieldbag["header"])["Rotation"],
|
|
285
|
+
)
|
|
286
|
+
rotation_matrix[
|
|
287
|
+
:,
|
|
288
|
+
direction_index,
|
|
289
|
+
] = cast(np.ndarray, rotation_column).transpose()
|
|
290
|
+
except Exception:
|
|
291
|
+
pass
|
|
292
|
+
|
|
293
|
+
if n_total_fields > n_fields:
|
|
294
|
+
field_list = attach_derivative_branches(
|
|
295
|
+
fieldbag=fieldbag,
|
|
296
|
+
field_list=field_list,
|
|
297
|
+
base_field_count=n_fields,
|
|
298
|
+
derivative_spec=derivative_spec,
|
|
299
|
+
spatial_shape=tuple(int(length) for length in x_grid.shape),
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
fieldbag["field"] = field_list
|
|
303
|
+
from ..results import FieldExportPayload
|
|
304
|
+
|
|
305
|
+
return FieldExportPayload(cast(Mapping[object, object], fieldbag), source=file_path)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _normalize_lattice(
|
|
309
|
+
lattice_object: np.ndarray,
|
|
310
|
+
*,
|
|
311
|
+
space_dim: int,
|
|
312
|
+
) -> np.ndarray:
|
|
313
|
+
"""Normalize `Grid.NPoints` into a flat three-axis integer lattice."""
|
|
314
|
+
|
|
315
|
+
lattice_raw: np.ndarray = np.asarray(lattice_object)
|
|
316
|
+
if lattice_raw.ndim == 0:
|
|
317
|
+
raise RuntimeError("Corrupted file.")
|
|
318
|
+
lattice: np.ndarray = lattice_raw.reshape(-1)
|
|
319
|
+
if lattice.size < space_dim:
|
|
320
|
+
raise RuntimeError("Corrupted file.")
|
|
321
|
+
lattice = lattice[:space_dim].astype(np.int64, copy=False)
|
|
322
|
+
if lattice.size < 3:
|
|
323
|
+
lattice = np.pad(lattice, (0, 3 - lattice.size), constant_values=1)
|
|
324
|
+
return lattice
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2001-2026 JCMwave GmbH
|
|
3
|
+
|
|
4
|
+
"""Nested mapping helpers for loader parsing code."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Mapping, MutableMapping, Sequence
|
|
9
|
+
|
|
10
|
+
PathComponent = str | int
|
|
11
|
+
Path = Sequence[PathComponent]
|
|
12
|
+
NestedMapping = MutableMapping[PathComponent, object]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def nested_get(mapping: Mapping[PathComponent, object], path: Path) -> object:
|
|
16
|
+
"""Return nested value at `path`.
|
|
17
|
+
|
|
18
|
+
Parameters
|
|
19
|
+
----------
|
|
20
|
+
mapping : Mapping[str | int, object]
|
|
21
|
+
Root mapping.
|
|
22
|
+
path : Sequence[str | int]
|
|
23
|
+
Nested key path.
|
|
24
|
+
|
|
25
|
+
Returns
|
|
26
|
+
-------
|
|
27
|
+
object
|
|
28
|
+
Value at the given nested path.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
current: object = mapping
|
|
32
|
+
component: PathComponent
|
|
33
|
+
for component in path:
|
|
34
|
+
if not isinstance(current, Mapping):
|
|
35
|
+
raise KeyError(
|
|
36
|
+
f"Path component {component!r} cannot be resolved on non-mapping node."
|
|
37
|
+
)
|
|
38
|
+
current = current[component]
|
|
39
|
+
return current
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def nested_set(mapping: NestedMapping, path: Path, value: object) -> None:
|
|
43
|
+
"""Set nested value at `path`.
|
|
44
|
+
|
|
45
|
+
Parameters
|
|
46
|
+
----------
|
|
47
|
+
mapping : MutableMapping[str | int, object]
|
|
48
|
+
Root mapping.
|
|
49
|
+
path : Sequence[str | int]
|
|
50
|
+
Nested key path.
|
|
51
|
+
value : object
|
|
52
|
+
Value written at the path.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
if not path:
|
|
56
|
+
raise ValueError("Nested path must not be empty.")
|
|
57
|
+
|
|
58
|
+
current: NestedMapping = mapping
|
|
59
|
+
component: PathComponent
|
|
60
|
+
for component in path[:-1]:
|
|
61
|
+
existing: object | None = current.get(component)
|
|
62
|
+
if isinstance(existing, MutableMapping):
|
|
63
|
+
current = existing
|
|
64
|
+
continue
|
|
65
|
+
|
|
66
|
+
new_child: dict[PathComponent, object] = {}
|
|
67
|
+
current[component] = new_child
|
|
68
|
+
current = new_child
|
|
69
|
+
current[path[-1]] = value
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2001-2026 JCMwave GmbH
|
|
3
|
+
|
|
4
|
+
"""Fourier-result to power-flux conversion helpers."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
from ..exceptions import InvalidConfigurationError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def convert_to_powerflux(
|
|
16
|
+
fourier_results: Mapping[str, object],
|
|
17
|
+
) -> dict[str, object]:
|
|
18
|
+
"""Convert Fourier transform results into power-flux density.
|
|
19
|
+
|
|
20
|
+
Parameters
|
|
21
|
+
----------
|
|
22
|
+
fourier_results : Mapping[str, object]
|
|
23
|
+
Fourier-transform postprocess result.
|
|
24
|
+
|
|
25
|
+
Returns
|
|
26
|
+
-------
|
|
27
|
+
dict[str, object]
|
|
28
|
+
Power-flux density result.
|
|
29
|
+
|
|
30
|
+
Raises
|
|
31
|
+
------
|
|
32
|
+
InvalidConfigurationError
|
|
33
|
+
If the Fourier-transform result does not contain the required title,
|
|
34
|
+
header, wave-vector, or field data.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
title_object: object | None = fourier_results.get("title")
|
|
38
|
+
if not isinstance(title_object, str):
|
|
39
|
+
raise InvalidConfigurationError(
|
|
40
|
+
"Invalid Fourier result payload: missing `title`."
|
|
41
|
+
)
|
|
42
|
+
title: str = title_object
|
|
43
|
+
|
|
44
|
+
field_type: str
|
|
45
|
+
if "ElectricFieldStrength" in title:
|
|
46
|
+
field_type = "ElectricFieldStrength"
|
|
47
|
+
elif "MagneticFieldStrength" in title:
|
|
48
|
+
field_type = "MagneticFieldStrength"
|
|
49
|
+
else:
|
|
50
|
+
raise InvalidConfigurationError(
|
|
51
|
+
"Invalid Fourier result payload: title does not include field type."
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
header_object: object | None = fourier_results.get("header")
|
|
55
|
+
if not isinstance(header_object, Mapping):
|
|
56
|
+
raise InvalidConfigurationError(
|
|
57
|
+
"Invalid Fourier result payload: missing `header`."
|
|
58
|
+
)
|
|
59
|
+
header: Mapping[str, object] = header_object
|
|
60
|
+
|
|
61
|
+
if "K" not in fourier_results:
|
|
62
|
+
return {
|
|
63
|
+
"title": title.replace(field_type, "PowerFluxDensity"),
|
|
64
|
+
"header": dict(header),
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
k_object: object | None = fourier_results.get("K")
|
|
68
|
+
fields_object: object | None = fourier_results.get(field_type)
|
|
69
|
+
if not isinstance(k_object, np.ndarray):
|
|
70
|
+
raise InvalidConfigurationError(
|
|
71
|
+
"Invalid Fourier result payload: `K` must be ndarray."
|
|
72
|
+
)
|
|
73
|
+
if not isinstance(fields_object, Mapping):
|
|
74
|
+
raise InvalidConfigurationError(
|
|
75
|
+
f"Invalid Fourier result payload: `{field_type}` must be a mapping."
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
rel_eps_object: object | None = header.get("RelPermittivity")
|
|
79
|
+
rel_mu_object: object | None = header.get("RelPermeability")
|
|
80
|
+
if not isinstance(rel_eps_object, (int, float, complex)):
|
|
81
|
+
raise InvalidConfigurationError(
|
|
82
|
+
"Invalid Fourier result payload: header missing numeric `RelPermittivity`."
|
|
83
|
+
)
|
|
84
|
+
if not isinstance(rel_mu_object, (int, float, complex)):
|
|
85
|
+
raise InvalidConfigurationError(
|
|
86
|
+
"Invalid Fourier result payload: header missing numeric `RelPermeability`."
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
try:
|
|
90
|
+
from scipy import constants
|
|
91
|
+
|
|
92
|
+
eps0: float = constants.epsilon_0
|
|
93
|
+
mu0: float = constants.mu_0
|
|
94
|
+
except Exception:
|
|
95
|
+
eps0 = 8.85418781762039e-12
|
|
96
|
+
mu0 = 1.25663706143592e-06
|
|
97
|
+
|
|
98
|
+
rel_eps: complex = complex(rel_eps_object)
|
|
99
|
+
rel_mu: complex = complex(rel_mu_object)
|
|
100
|
+
eps: float = float(np.real(rel_eps * eps0))
|
|
101
|
+
mu: float = float(np.real(rel_mu * mu0))
|
|
102
|
+
k: np.ndarray = k_object
|
|
103
|
+
|
|
104
|
+
factor: float
|
|
105
|
+
if field_type == "ElectricFieldStrength":
|
|
106
|
+
factor = 0.5 * float(np.sqrt(eps / mu))
|
|
107
|
+
else:
|
|
108
|
+
factor = 0.5 * float(np.sqrt(mu / eps))
|
|
109
|
+
|
|
110
|
+
power_fields: dict[int, np.ndarray] = {}
|
|
111
|
+
k_holographic_norm: np.ndarray = np.linalg.norm(k, axis=1)
|
|
112
|
+
ones: np.ndarray = np.ones((3, 1))
|
|
113
|
+
|
|
114
|
+
field_index: object
|
|
115
|
+
field_value: object
|
|
116
|
+
for field_index, field_value in fields_object.items():
|
|
117
|
+
if not isinstance(field_index, int):
|
|
118
|
+
raise InvalidConfigurationError(
|
|
119
|
+
"Invalid Fourier result payload: field index keys must be integers."
|
|
120
|
+
)
|
|
121
|
+
if not isinstance(field_value, np.ndarray):
|
|
122
|
+
raise InvalidConfigurationError(
|
|
123
|
+
"Invalid Fourier result payload: field values must be ndarray."
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
norm_field: np.ndarray = (
|
|
127
|
+
np.sum(np.square(np.abs(field_value)), axis=1) / k_holographic_norm
|
|
128
|
+
)
|
|
129
|
+
kron_field: np.ndarray = np.kron(ones, norm_field).T
|
|
130
|
+
power_fields[field_index] = factor * kron_field * k
|
|
131
|
+
|
|
132
|
+
return {
|
|
133
|
+
"title": title.replace(field_type, "PowerFluxDensity"),
|
|
134
|
+
"header": dict(header),
|
|
135
|
+
"PowerFluxDensity": power_fields,
|
|
136
|
+
}
|