Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/ascii_helpers.py: 100%
28 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 11:58 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 11:58 +0000
1# Copyright (C) 2026 Henrik Finsberg and Simula Research Laboratory
2#
3# This file is part of io4dolfinx
4#
5# SPDX-License-Identifier: MIT
7"""
8Helpers for reading and writing ASCII files with a header followed by one row per line
9"""
11from __future__ import annotations
13import warnings
14from collections.abc import Sequence
15from pathlib import Path
17import numpy as np
18import numpy.typing as npt
20__all__ = ["read_count", "check_row_count", "read_rows", "write_rows"]
23def read_count(path: Path) -> int:
24 """Read the number on the first line of a file."""
25 with open(path) as f:
26 return int(f.readline().split()[0])
29def check_row_count(path: Path, expected: int, header: int = 1):
30 """Check that a file has ``expected`` non-empty lines after its header.
32 Raises:
33 ValueError: If the number of lines differs.
34 """
35 with open(path) as f:
36 num_rows = sum(1 for line in f if line.strip()) - header
37 if num_rows != expected:
38 raise ValueError(f"{path} has {num_rows} rows after its header, expected {expected}.")
41def read_rows(
42 path: Path,
43 num_columns: int,
44 local_range: tuple[int, int] | list[int] | None = None,
45 header: int = 1,
46 dtype: npt.DTypeLike = np.str_,
47 usecols: int | Sequence[int] | None = None,
48) -> npt.NDArray:
49 """Read rows after the header of a file.
51 Args:
52 path: The file
53 num_columns: Number of columns read, used to shape an empty result
54 local_range: Range ``[start, end)`` of rows to read, all rows if ``None``
55 header: Number of header lines
56 dtype: Type of the values. Read numeric columns with a numeric type: as
57 strings, every value takes several times the memory.
58 usecols: Columns to read, all if ``None``
60 Returns:
61 The rows, of shape ``(num_rows, num_columns)``
62 """
63 start = 0 if local_range is None else int(local_range[0])
64 max_rows = None if local_range is None else int(local_range[1]) - start
65 if max_rows == 0:
66 return np.zeros((0, num_columns), dtype=dtype)
67 with warnings.catch_warnings():
68 # A file without rows is valid, e.g. a marker without entities
69 warnings.filterwarnings("ignore", message="loadtxt: input contained no data")
70 rows = np.loadtxt(
71 path,
72 dtype=dtype,
73 skiprows=header + start,
74 max_rows=max_rows,
75 ndmin=2,
76 usecols=usecols,
77 )
78 return rows.reshape(0, num_columns) if rows.size == 0 else rows
81def write_rows(path: Path, header: list[str], rows: npt.NDArray, fmt: str):
82 """Write header lines followed by one formatted line per row."""
83 with open(path, "w") as f:
84 f.write("\n".join(header) + "\n")
85 np.savetxt(f, rows, fmt=fmt)