Source code for jcmsuite.loaders.table

# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH

"""JCM table loader."""

from __future__ import annotations

import re
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, BinaryIO, Literal, TypeAlias, cast

import numpy as np

from ..exceptions import InvalidConfigurationError, UnsupportedExportError
from .blob_header import BlobHeaderReader
from .nested_mapping import PathComponent, nested_get, nested_set

if TYPE_CHECKING:
    import pandas as pd

    from ..results.internal.export.xarray.types import XarrayDataTree
    from ..results.payloads import TableCollectionPayload, TablePayload

SingleTableData: TypeAlias = dict[PathComponent, object]


@dataclass(slots=True)
class TableColumn:
    """Column descriptor extracted from a table blob."""

    name: str
    dtype: str
    data: np.ndarray


class TableCollection(list[SingleTableData]):
    """List-compatible result for `.jcm` files containing multiple tables.

    Parameters
    ----------
    tables : list[SingleTableData]
        Parsed tables in file order.
    source_file : Path | None, optional
        Source file used for metadata in exports.
    """

    def __init__(
        self,
        tables: list[SingleTableData],
        *,
        source_file: Path | None = None,
    ) -> None:

        super().__init__(tables)
        self.source_file: Path | None = source_file

    def table_names(self) -> tuple[str, ...]:
        """Return deterministic, title-based names for table exports."""

        return _unique_table_names(self)

    def to_df(self, orient: str | None = None) -> "pd.DataFrame":
        """Export all named tables into one long-form pandas DataFrame."""

        if orient not in (None, "long"):
            if orient == "wide":
                raise UnsupportedExportError(
                    "to_df is not supported for wide table collections."
                )
            raise ValueError("orient must be None, 'wide', or 'long'")

        from ..results.pandas_export import _table_collection_to_df

        return _table_collection_to_df(
            self,
            self.table_names(),
            tuple(_table_title(table_payload) for table_payload in self),
        )

    def to_xarray(self) -> "XarrayDataTree":
        """Export all named tables into a title-keyed `DataTree`."""

        from ..results.internal.export.companion_xarray import require_xarray_companion

        require_xarray_companion()
        from jcmsuite_xarray.tables import table_collection_to_xarray

        return table_collection_to_xarray(
            self,
            self.table_names(),
            source_file=self.source_file,
        )


[docs] def load_table( file_name: str | Path, *, format: Literal["named"] = "named", ) -> "TablePayload | TableCollectionPayload": """Load table data from a `.jcm` file. Parameters ---------- file_name : str | Path Path to the table file. format : {"named"}, optional Output format. The only supported value is `"named"`. Returns ------- TablePayload | TableCollectionPayload One table, or an ordered collection if the file contains multiple tables. Raises ------ InvalidConfigurationError If `file_name` is not a file or `format` is not `"named"`. """ file_path: Path = Path(file_name).expanduser().resolve() if not file_path.is_file(): raise InvalidConfigurationError("file_name -> file path expected.") if format != "named": raise InvalidConfigurationError( "Only the canonical `named` table output format is supported." ) with open(file_path, "rb") as stream: tables: list[SingleTableData] = [] while True: tables.append(_load_single_table(stream)) at_end: bool = True while True: previous_position: int = stream.tell() header_start: str = stream.readline().decode() if stream.tell() == previous_position: break header_start = ( header_start.replace(" ", "").replace("\r\n", "").replace("\n", "") ) if not header_start: continue if header_start == "/*<BLOBHead>": at_end = False stream.seek(previous_position) break if at_end: break if len(tables) == 1: loaded_table: SingleTableData = tables[0] from ..results.postprocess_payloads import _StandaloneTablePayload return cast( "TablePayload | TableCollectionPayload", _StandaloneTablePayload( cast(Mapping[object, object], loaded_table), source=file_path, ), ) collection = TableCollection(tables, source_file=file_path) from ..results.postprocess_payloads import _StandaloneTableCollectionPayload return _StandaloneTableCollectionPayload(collection)
def _unique_table_names(tables: list[SingleTableData]) -> tuple[str, ...]: """Return title-derived table names with deterministic duplicate suffixes.""" seen_counts: dict[str, int] = {} names: list[str] = [] table_index: int table_payload: SingleTableData for table_index, table_payload in enumerate(tables): base_name: str = _table_title(table_payload) or f"table_{table_index}" base_name = base_name.replace("/", "_") or f"table_{table_index}" seen_count: int = seen_counts.get(base_name, 0) seen_counts[base_name] = seen_count + 1 if seen_count == 0: names.append(base_name) continue names.append(f"{base_name}_{seen_count}") return tuple(names) def _table_title(table_payload: SingleTableData) -> str | None: """Return a table title from named table payloads when available.""" if not isinstance(table_payload, dict): return None title_object: object | None = table_payload.get("title") if isinstance(title_object, str): return title_object return None def _load_single_table(stream: BinaryIO) -> SingleTableData: """Load single table. Parameters ---------- stream : BinaryIO Value passed via ``stream``. Returns ------- SingleTableData Decoded single-table payload. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ header: dict[PathComponent, object] = BlobHeaderReader( stream, "Table" ).read_header() table: dict[PathComponent, object] = {"title": header["Title"]} if "MetaData" in header: table["header"] = header["MetaData"] n_columns: int = _coerce_int(header.get("NColumns"), key_name="NColumns") n_rows: int = _coerce_int(header.get("NRows"), key_name="NRows") columns: list[TableColumn] = _parse_column_metadata(header, n_columns, n_rows) _read_column_payload(stream, header=header, columns=columns, n_rows=n_rows) _populate_named_table( table=table, columns=columns, n_rows=n_rows, ) return table def _coerce_int(value: object, *, key_name: str) -> int: """Coerce integer to expected type. Parameters ---------- value : object Input value(s) to convert into normalized representation. key_name : str Value passed via ``key_name``. Returns ------- int Parsed numeric value. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ if isinstance(value, bool) or not isinstance(value, (int, np.integer)): raise RuntimeError(f"File corrupted: `{key_name}` missing or invalid.") return int(value) def _parse_column_metadata( header: dict[PathComponent, object], n_columns: int, n_rows: int, ) -> list[TableColumn]: """Parse column metadata. Parameters ---------- header : dict[PathComponent, object] Value passed via ``header``. n_columns : int Value passed via ``n_columns``. n_rows : int Value passed via ``n_rows``. Returns ------- list[TableColumn] Normalized list output. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ columns: list[TableColumn] = [] column_index: int for column_index in range(n_columns): column_key: str = f"Column{column_index + 1}" column_header_object: object | None = header.get(column_key) if not isinstance(column_header_object, dict): raise RuntimeError("File corrupted: column metadata is missing.") column_header: dict[PathComponent, object] = column_header_object name_object: object | None = column_header.get("Name") type_object: object | None = column_header.get("Type") if not isinstance(name_object, str) or not isinstance(type_object, str): raise RuntimeError("File corrupted: column name/type is missing.") dtype: str if type_object == "int": dtype = "int32" elif type_object == "double": dtype = "float64" elif type_object == "doublecomplex": dtype = "complex128" else: raise RuntimeError("File corrupted: unsupported column type.") columns.append( TableColumn( name=name_object, dtype=dtype, data=np.ndarray((n_rows,), dtype=dtype), ) ) return columns def _read_column_payload( stream: BinaryIO, *, header: dict[PathComponent, object], columns: list[TableColumn], n_rows: int, ) -> None: """Read column payload. Parameters ---------- stream : BinaryIO Value passed via ``stream``. header : dict[PathComponent, object] Value passed via ``header``. columns : list[TableColumn] Value passed via ``columns``. n_rows : int Value passed via ``n_rows``. Returns ------- None No value is returned. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ mode_object: object | None = header.get("__MODE__") mode: str = cast(str, mode_object) try: if mode == "BINARY": column: TableColumn for column in columns: column.data = np.fromfile(stream, column.dtype, n_rows) return n_columns: int = len(columns) n_entries: int = n_rows * n_columns entry_index: int = 0 while entry_index < n_entries: line: str = stream.readline().decode() # Complex text rows may include spaces after `(` and `,`. # We normalize both so token splitting remains stable. line = re.sub(r"\([ ]*", "(", line) line = re.sub(r",[ ]*", ",", line) token_line: list[str] = line.split("#")[0].split() token: str for token in token_line: current_column: TableColumn = columns[entry_index % n_columns] row_index: int = entry_index // n_columns if current_column.dtype == "int32": current_column.data[row_index] = int(token) elif current_column.dtype == "float64": current_column.data[row_index] = float(token) else: tag_real, tag_imag = token.split(",") current_column.data[row_index] = complex( float(tag_real[1:]), float(tag_imag[:-1]), ) entry_index += 1 except Exception as error: raise RuntimeError("File corrupted.") from error def _populate_named_table( *, table: dict[PathComponent, object], columns: list[TableColumn], n_rows: int, ) -> None: """Populate nested named-table output from parsed column metadata. Parameters ---------- table : dict[PathComponent, object] Value passed via ``table``. columns : list[TableColumn] Value passed via ``columns``. n_rows : int Value passed via ``n_rows``. Returns ------- None No value is returned. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ fix_path_format: list[list[PathComponent]] = [] last_path: list[PathComponent] = [] column: TableColumn for column in columns: key: str = column.name # Regex captures derivative form `d(A)_b` and rewrites it so we can split # by a placeholder separator into deterministic nested-dict path parts. def derivative_placeholder(match: re.Match[str]) -> str: return f"d_{match.group(2)}<DerivativeSep>{match.group(1)}" key = re.sub(r"d\((.*)\)_(.*)", derivative_placeholder, key) key = re.sub(r"d\((.*)\)_(.*)", derivative_placeholder, key) name_indices: list[int] = [] while True: name_index: re.Match[str] | None = re.search(r"(.*)(_\d{1,})", key) if name_index is None: break key = name_index.group(1) name_indices.append(int(name_index.group(2)[1:]) - 1) name_indices.reverse() vector_index: int = -1 if key.endswith("X"): vector_index = 0 key = key[:-1] elif key.endswith("Y"): vector_index = 1 key = key[:-1] elif key.endswith("Z"): vector_index = 2 key = key[:-1] path: list[PathComponent] = cast( list[PathComponent], key.split("<DerivativeSep>") + name_indices, ) if vector_index > -1: if last_path != path: try: value_np: object = nested_get(table, path) except KeyError: value_np = np.ndarray((n_rows, 3), dtype=column.dtype) else: value_np = nested_get(table, path) if not isinstance(value_np, np.ndarray): raise RuntimeError("File corrupted: expected ndarray at vector path.") value_np[:, vector_index] = column.data nested_set(table, path, value_np) elif len(name_indices) == 2: nested_set(table, path, column.data) fix_path_format.append( cast(list[PathComponent], key.split("<DerivativeSep>")) ) elif len(name_indices) > 2: name_indices.insert(0, name_indices.pop()) path = cast( list[PathComponent], key.split("<DerivativeSep>") + name_indices, ) nested_set(table, path, column.data) fix_path_format.append( cast( list[PathComponent], key.split("<DerivativeSep>") + [name_indices[0]], ) ) else: nested_set(table, path, column.data) last_path = path if fix_path_format: _convert_to_array(table, fix_path_format) def _convert_to_array( table: dict[PathComponent, object], fix_path_format: list[list[PathComponent]], ) -> None: """Convert to array. Parameters ---------- table : dict[PathComponent, object] Value passed via ``table``. fix_path_format : list[list[PathComponent]] Filesystem path supplied via `fix_path_format`. Returns ------- None No value is returned. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ path: list[PathComponent] for path in fix_path_format: value_object: object = nested_get(table, path) if isinstance(value_object, np.ndarray): continue if not isinstance(value_object, dict): raise RuntimeError( "File corrupted: expected nested dictionary for conversion." ) array_representation: np.ndarray = np.moveaxis( _convert_dict_to_array(value_object), -1, 0, ) nested_set(table, path, array_representation) def _convert_dict_to_array(value_dict: dict[PathComponent, object]) -> np.ndarray: """Convert dict to array. Parameters ---------- value_dict : dict[PathComponent, object] Value passed via ``value_dict``. Returns ------- np.ndarray Computed ``np.ndarray`` value. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ values: list[object] = [] value: object for value in value_dict.values(): if isinstance(value, np.ndarray): values.append(value) elif isinstance(value, dict): values.append(_convert_dict_to_array(value)) else: raise RuntimeError( "File corrupted: unexpected scalar while converting arrays." ) return np.array(values)