# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH
"""Cartesian fieldbag loader."""
from __future__ import annotations
from collections.abc import Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Literal, cast
import numpy as np
from ..exceptions import InvalidConfigurationError
from .blob_header import BlobHeaderReader
from .cartesian_field_reader import (
_coerce_int,
_FieldMode,
_FieldPayloadReader,
attach_derivative_branches,
field_block_count,
read_parameter_derivatives,
)
from .nested_mapping import nested_get, nested_set
if TYPE_CHECKING:
from ..results import FieldExportPayload
CartesianFieldFormat = Literal["squeeze", "full"]
[docs]
def load_cartesian_fields(
file_name: str | Path,
*,
format: CartesianFieldFormat = "squeeze",
) -> "FieldExportPayload":
"""Load field values on a Cartesian grid.
Parameters
----------
file_name : str | Path
Path to a Cartesian fieldbag `.jcm` file.
format : {"squeeze", "full"}, optional
Shape of the returned coordinate arrays and field values. `"squeeze"`
removes dimensions of length 1. `"full"` keeps all dimensions. The
method supports text and binary fieldbag files.
Returns
-------
FieldExportPayload
Coordinates, field values, available derivatives, and file
information.
Raises
------
InvalidConfigurationError
If `file_name` is not a file or `format` is not supported.
RuntimeError
If the fieldbag file is damaged or uses an unsupported storage format.
"""
file_path: Path = Path(file_name).expanduser().resolve()
if not file_path.is_file():
raise InvalidConfigurationError("file_name -> file path expected.")
if format not in {"squeeze", "full"}:
raise InvalidConfigurationError("Invalid format.")
with open(file_path, "rb") as stream:
header: dict[str | int, object] = BlobHeaderReader(
stream,
"CartesianFieldBag",
).read_header()
n_fields: int = _coerce_int(header.get("NFields"), key_name="NFields")
n_subfields: int = 0
while True:
tensor_vector_object: object | None = header.get("TensorQuantityVector")
if not isinstance(tensor_vector_object, Mapping):
break
if n_subfields not in tensor_vector_object:
break
n_subfields += 1
n_components: list[int] = []
subfield_index: int
for subfield_index in range(n_subfields):
tensor_vector = cast(
Mapping[str | int, object], header["TensorQuantityVector"]
)
component_header_object: object = tensor_vector[subfield_index]
if not isinstance(component_header_object, Mapping):
raise RuntimeError("Corrupted file.")
n_components.append(
_coerce_int(
component_header_object.get("NComponents"),
key_name=f"TensorQuantityVector[{subfield_index}].NComponents",
)
)
grid_object: object | None = header.get("Grid")
if not isinstance(grid_object, Mapping):
raise RuntimeError("Corrupted file.")
space_dim: int = _coerce_int(
grid_object.get("SpaceDim"), key_name="Grid.SpaceDim"
)
lattice_object: object | None = grid_object.get("NPoints")
if not isinstance(lattice_object, np.ndarray):
raise RuntimeError("Corrupted file.")
lattice: np.ndarray = _normalize_lattice(
lattice_object,
space_dim=space_dim,
)
lattice_values: tuple[int, ...] = tuple(
int(axis_length) for axis_length in lattice
)
if len(lattice_values) != 3:
raise RuntimeError("Corrupted file.")
lattice_shape: tuple[int, int, int] = (
lattice_values[0],
lattice_values[1],
lattice_values[2],
)
n_points: int = int(np.prod(lattice_shape))
n_cells: int = int(
np.prod([max(axis_length - 1, 1) for axis_length in lattice_shape])
)
mode_raw: object | None = header.get("__MODE__")
if not isinstance(mode_raw, str):
raise RuntimeError("Corrupted file.")
mode: str = mode_raw
if mode == "BINARY0":
zero_marker: bytes = stream.read(1)
if zero_marker != b"0":
raise RuntimeError("Corrupted file.")
mode = "BINARY"
if mode not in {"BINARY", "TEXT"}:
raise RuntimeError("File not in binary format.")
derivative_spec = read_parameter_derivatives(header)
n_total_fields: int = field_block_count(
base_field_count=n_fields,
derivative_spec=derivative_spec,
)
reader: _FieldPayloadReader = _FieldPayloadReader.from_stream(
stream=stream,
mode=cast(_FieldMode, mode),
)
fieldbag: dict[str, object] = {}
points: list[np.ndarray] = [
np.arange(0, 0.1, 0.1),
np.arange(0, 0.1, 0.1),
np.arange(0, 0.1, 0.1),
]
field_list: list[np.ndarray] = []
fieldbag["field"] = field_list
try:
axis_index: int
for axis_index in range(space_dim):
points[axis_index] = reader.read_numeric_array(
dtype=np.float64,
count=lattice_shape[axis_index],
)
contains_domain_ids: bool = False
try:
contains_domain_ids = (
cast(str, nested_get(header, ["Grid", "ContainsDomainIds"]))
== "yes"
)
except KeyError:
contains_domain_ids = False
try:
contains_domain_ids = (
cast(str, nested_get(header, ["Grid", "ContainsMaterialIds"]))
== "yes"
)
except KeyError:
pass
if contains_domain_ids:
nested_set(
cast(dict[str | int, object], fieldbag),
["grid", "domainIds"],
reader.read_numeric_array(
dtype=np.int32,
count=n_cells,
),
)
n_comp: int = n_components[0]
field_index: int
for field_index in range(n_total_fields):
values: np.ndarray = reader.read_complex_array(
component_count=n_comp,
point_count=n_points,
)
values = values.reshape((n_points, n_comp), copy=False)
field_list.append(values)
except Exception as error:
raise RuntimeError("Corrupted file.") from error
tensor_vector = cast(Mapping[str | int, object], header["TensorQuantityVector"])
first_tensor = cast(Mapping[str | int, object], tensor_vector[0])
polarization: str = cast(str, first_tensor["Polarization"])
quantity_type: str = cast(str, first_tensor["Type"])
if polarization != "xyz" and "Strength" in quantity_type:
indices: list[int] = []
axis_index = 0
for axis_index in range(3):
if polarization.count("xyz"[axis_index]):
indices.append(axis_index)
field_index = 0
for field_index in range(n_total_fields):
polarization_data: np.ndarray = field_list[field_index]
field_list[field_index] = np.ndarray(
(polarization_data.shape[0], 3),
dtype="complex128",
)
field_list[field_index].fill(0.0)
field_list[field_index][:, indices] = polarization_data
n_comp = 3
else:
n_comp = n_components[0]
x_grid: np.ndarray = np.ndarray(lattice_shape)
y_grid: np.ndarray = np.ndarray(lattice_shape)
z_grid: np.ndarray = np.ndarray(lattice_shape)
y_index: int
z_index: int
for y_index in range(lattice_shape[1]):
for z_index in range(lattice_shape[2]):
x_grid[:, y_index, z_index] = points[0]
x_index: int
for x_index in range(lattice_shape[0]):
for z_index in range(lattice_shape[2]):
y_grid[x_index, :, z_index] = points[1]
for x_index in range(lattice_shape[0]):
for y_index in range(lattice_shape[1]):
z_grid[x_index, y_index, :] = points[2]
if format == "squeeze":
x_grid = np.squeeze(x_grid)
y_grid = np.squeeze(y_grid)
z_grid = np.squeeze(z_grid)
if header.get("CoordinateSystem") == "Polar":
fieldbag["Theta"] = x_grid
fieldbag["Phi"] = y_grid
fieldbag["R"] = z_grid
else:
fieldbag["X"] = x_grid
fieldbag["Y"] = y_grid
fieldbag["Z"] = z_grid
shape: list[int] = list(x_grid.shape)
shape.append(n_comp)
field_index = 0
for field_index in range(n_fields):
field_list[field_index] = field_list[field_index].reshape(shape, order="F")
try:
fieldbag["header"] = {
"Origin": cast(Mapping[str | int, object], header["Grid"])["Origin"],
"Rotation": np.eye(3),
"QuantityType": quantity_type,
}
rotation_direction: str
for direction_index, rotation_direction in enumerate(["X", "Y", "Z"]):
rotation_column = cast(
Mapping[str | int, object],
header["Grid"],
)[f"Rotation{rotation_direction}"]
rotation_matrix: np.ndarray = cast(
np.ndarray,
cast(dict[str, object], fieldbag["header"])["Rotation"],
)
rotation_matrix[
:,
direction_index,
] = cast(np.ndarray, rotation_column).transpose()
except Exception:
pass
if n_total_fields > n_fields:
field_list = attach_derivative_branches(
fieldbag=fieldbag,
field_list=field_list,
base_field_count=n_fields,
derivative_spec=derivative_spec,
spatial_shape=tuple(int(length) for length in x_grid.shape),
)
fieldbag["field"] = field_list
from ..results import FieldExportPayload
return FieldExportPayload(cast(Mapping[object, object], fieldbag), source=file_path)
def _normalize_lattice(
lattice_object: np.ndarray,
*,
space_dim: int,
) -> np.ndarray:
"""Normalize `Grid.NPoints` into a flat three-axis integer lattice."""
lattice_raw: np.ndarray = np.asarray(lattice_object)
if lattice_raw.ndim == 0:
raise RuntimeError("Corrupted file.")
lattice: np.ndarray = lattice_raw.reshape(-1)
if lattice.size < space_dim:
raise RuntimeError("Corrupted file.")
lattice = lattice[:space_dim].astype(np.int64, copy=False)
if lattice.size < 3:
lattice = np.pad(lattice, (0, 3 - lattice.size), constant_values=1)
return lattice