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 12:02 +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 

6 

7""" 

8Helpers for reading and writing ASCII files with a header followed by one row per line 

9""" 

10 

11from __future__ import annotations 

12 

13import warnings 

14from collections.abc import Sequence 

15from pathlib import Path 

16 

17import numpy as np 

18import numpy.typing as npt 

19 

20__all__ = ["read_count", "check_row_count", "read_rows", "write_rows"] 

21 

22 

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]) 

27 

28 

29def check_row_count(path: Path, expected: int, header: int = 1): 

30 """Check that a file has ``expected`` non-empty lines after its header. 

31 

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}.") 

39 

40 

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. 

50 

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`` 

59 

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 

79 

80 

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)