Skip to content

API Reference

Complete reference for all pyhfm functions, classes, and modules.

Main Functions

pyhfm.read_hfm(file_path, *, return_metadata=False, config=None)

read_hfm(
    file_path: str | Path,
    *,
    return_metadata: Literal[False] = False,
    config: dict[str, Any] | None = None,
) -> pa.Table
read_hfm(
    file_path: str | Path,
    *,
    return_metadata: Literal[True],
    config: dict[str, Any] | None = None,
) -> tuple[FileMetadata, pa.Table]

Read and parse an HFM data file.

This is the main entry point for reading Heat Flow Meter (HFM) data files. The function returns a PyArrow table with embedded metadata by default, or optionally returns a tuple of (metadata, table) for more detailed access.

Parameters:

Name Type Description Default
file_path str | Path

Path to the HFM file (.tst format)

required
return_metadata bool

If True, return (metadata, table) tuple instead of just table

False
config dict[str, Any] | None

Optional configuration overrides for parsing

None

Returns:

Type Description
Table | tuple[FileMetadata, Table]

PyArrow table with embedded metadata, or tuple of (metadata, table)

Table | tuple[FileMetadata, Table]

if return_metadata=True

Raises:

Type Description
HFMFileError

If file cannot be read or doesn't exist

HFMParsingError

If file parsing fails

HFMUnsupportedFormatError

If file format is not supported

HFMValidationError

If data validation fails

Examples:

Basic usage:

>>> import polars as pl
>>> table = read_hfm("sample.tst")
>>> print(table.schema)
>>> print(pl.from_arrow(table))

Access metadata separately:

>>> metadata, table = read_hfm("sample.tst", return_metadata=True)
>>> print(metadata["sample_id"])
>>> print(metadata["type"])

Custom configuration:

>>> config = {"default_encoding": "utf-8"}
>>> table = read_hfm("sample.tst", config=config)
Source code in src/pyhfm/api/loaders.py
def read_hfm(
    file_path: str | Path,
    *,
    return_metadata: bool = False,
    config: dict[str, Any] | None = None,
) -> pa.Table | tuple[FileMetadata, pa.Table]:
    """Read and parse an HFM data file.

    This is the main entry point for reading Heat Flow Meter (HFM) data files.
    The function returns a PyArrow table with embedded metadata by default, or
    optionally returns a tuple of (metadata, table) for more detailed access.

    Args:
        file_path: Path to the HFM file (.tst format)
        return_metadata: If True, return (metadata, table) tuple instead of just table
        config: Optional configuration overrides for parsing

    Returns:
        PyArrow table with embedded metadata, or tuple of (metadata, table)
        if return_metadata=True

    Raises:
        HFMFileError: If file cannot be read or doesn't exist
        HFMParsingError: If file parsing fails
        HFMUnsupportedFormatError: If file format is not supported
        HFMValidationError: If data validation fails

    Examples:
        Basic usage:
        >>> import polars as pl
        >>> table = read_hfm("sample.tst")
        >>> print(table.schema)
        >>> print(pl.from_arrow(table))

        Access metadata separately:
        >>> metadata, table = read_hfm("sample.tst", return_metadata=True)
        >>> print(metadata["sample_id"])
        >>> print(metadata["type"])

        Custom configuration:
        >>> config = {"default_encoding": "utf-8"}
        >>> table = read_hfm("sample.tst", config=config)
    """
    try:
        # Initialize parser with optional config
        parser = HFMParser(config)

        # Parse the file
        table = parser.parse_file(file_path)

        if return_metadata:
            # Extract metadata from table
            table_metadata = table.schema.metadata
            if table_metadata and b"file_metadata" in table_metadata:
                # Deserialize the metadata from JSON bytes
                file_metadata_bytes = table_metadata[b"file_metadata"]
                file_metadata = json.loads(file_metadata_bytes.decode("utf-8"))
                return file_metadata, table
            # Fallback - re-parse to get metadata
            metadata_parser = HFMParser(config)
            metadata_table = metadata_parser.parse_file(file_path)
            metadata_dict = metadata_table.schema.metadata
            if metadata_dict and b"file_metadata" in metadata_dict:
                file_metadata_bytes = metadata_dict[b"file_metadata"]
                file_metadata = json.loads(file_metadata_bytes.decode("utf-8"))
                return file_metadata, table
            return {}, table

    except HFMError:
        # Re-raise HFM-specific errors as-is
        raise
    except Exception as e:
        # Wrap unexpected errors
        error_msg = f"Unexpected error reading HFM file: {e}"
        raise HFMError(error_msg, str(file_path)) from e
    else:
        return table

Core Modules

Parser

pyhfm.core.parser.HFMParser

Main parser for HFM data files.

This class maintains backward compatibility while delegating to the new modular FileParser architecture.

Source code in src/pyhfm/core/parser.py
class HFMParser:
    """Main parser for HFM data files.

    This class maintains backward compatibility while delegating to the new
    modular FileParser architecture.
    """

    def __init__(self, config: dict[str, Any] | None = None) -> None:
        """Initialize HFM parser.

        Args:
            config: Optional configuration overrides
        """
        self._file_parser = FileParser(config)

    def parse_file(self, file_path: str | Path) -> pa.Table:
        """Parse an HFM file and return PyArrow table.

        Args:
            file_path: Path to HFM file

        Returns:
            PyArrow table with embedded metadata

        Raises:
            HFMFileError: If file cannot be read
            HFMUnsupportedFormatError: If file format not supported
            HFMParsingError: If parsing fails
        """
        return self._file_parser.parse_file(file_path)

    @property
    def config(self) -> Any:
        """Access to parser configuration for backward compatibility."""
        return self._file_parser.config

    # Expose parser methods for backward compatibility with tests
    def _extract_value_and_unit(self, sub_line: str) -> dict[str, float | str]:
        """Extract value and unit from a line using pre-compiled patterns."""
        return self._file_parser._extract_value_and_unit(sub_line)

    def _is_comment_line(self, line: str) -> bool:
        """Check if line is a comment."""
        return self._file_parser._is_comment_line(line)

    def _parse_date(self, line: str) -> str | None:
        """Parse date from a line."""
        return self._file_parser._parse_date(line)

Attributes

config property

Access to parser configuration for backward compatibility.

Methods:

__init__(config=None)

Initialize HFM parser.

Parameters:

Name Type Description Default
config dict[str, Any] | None

Optional configuration overrides

None
Source code in src/pyhfm/core/parser.py
def __init__(self, config: dict[str, Any] | None = None) -> None:
    """Initialize HFM parser.

    Args:
        config: Optional configuration overrides
    """
    self._file_parser = FileParser(config)

parse_file(file_path)

Parse an HFM file and return PyArrow table.

Parameters:

Name Type Description Default
file_path str | Path

Path to HFM file

required

Returns:

Type Description
Table

PyArrow table with embedded metadata

Raises:

Type Description
HFMFileError

If file cannot be read

HFMUnsupportedFormatError

If file format not supported

HFMParsingError

If parsing fails

Source code in src/pyhfm/core/parser.py
def parse_file(self, file_path: str | Path) -> pa.Table:
    """Parse an HFM file and return PyArrow table.

    Args:
        file_path: Path to HFM file

    Returns:
        PyArrow table with embedded metadata

    Raises:
        HFMFileError: If file cannot be read
        HFMUnsupportedFormatError: If file format not supported
        HFMParsingError: If parsing fails
    """
    return self._file_parser.parse_file(file_path)

Data Extractor

pyhfm.extractors.data_extractor.DataExtractor

Extracts tabular data from HFM metadata.

Source code in src/pyhfm/extractors/data_extractor.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
class DataExtractor:
    """Extracts tabular data from HFM metadata."""

    def __init__(self, config: dict[str, Any] | None = None) -> None:
        """Initialize data extractor.

        Args:
            config: Optional configuration overrides
        """
        self.config = DEFAULT_COLUMN_CONFIG
        if config:
            # Apply configuration overrides
            for key, value in config.items():
                if hasattr(self.config, key):
                    setattr(self.config, key, value)

    def extract_data(self, metadata: FileMetadata) -> pa.Table:
        """Extract data from metadata and return PyArrow table.

        Args:
            metadata: HFM metadata dictionary

        Returns:
            PyArrow table with measurement data

        Raises:
            HFMDataExtractionError: If data extraction fails
        """
        measurement_type = metadata.get("type")
        if not measurement_type:
            error_msg = "Missing measurement type in metadata"
            raise HFMDataExtractionError(
                error_msg,
                measurement_type=measurement_type,
            )

        try:
            if measurement_type == HFMType.CONDUCTIVITY.value:
                return self._extract_conductivity_data(metadata)
            if measurement_type == HFMType.VOLUMETRIC_HEAT_CAPACITY.value:
                return self._extract_heat_capacity_data(metadata)

            # Handle unsupported measurement type
            self._raise_unsupported_type_error(measurement_type)
        except Exception as e:
            if isinstance(e, HFMDataExtractionError):
                raise
            error_msg = f"Failed to extract data: {e}"
            raise HFMDataExtractionError(
                error_msg,
                measurement_type=measurement_type,
            ) from e

    def _raise_unsupported_type_error(self, measurement_type: str) -> NoReturn:
        """Raise error for unsupported measurement type."""
        error_msg = f"Unsupported measurement type: {measurement_type}"
        raise HFMDataExtractionError(
            error_msg,
            measurement_type=measurement_type,
        )

    def _extract_temperature_data_safely(
        self, value: dict[str, Any]
    ) -> tuple[dict[str, Any], dict[str, Any]]:
        """Safely extract upper and lower temperature data from a setpoint value.

        Args:
            value: Setpoint dictionary containing temperature data

        Returns:
            Tuple of (upper_temp_data, lower_temp_data) dictionaries
        """
        temp_data_item_raw = value.get("temperature", {})
        temp_data_item: dict[str, Any] = (
            temp_data_item_raw if isinstance(temp_data_item_raw, dict) else {}
        )

        if isinstance(temp_data_item, dict):
            upper_temp_raw: dict[str, Any] | float | str = temp_data_item.get(
                "upper", {}
            )
            lower_temp_raw: dict[str, Any] | float | str = temp_data_item.get(
                "lower", {}
            )
            upper_temp_data = upper_temp_raw if isinstance(upper_temp_raw, dict) else {}
            lower_temp_data = lower_temp_raw if isinstance(lower_temp_raw, dict) else {}
        else:
            upper_temp_data = {}
            lower_temp_data = {}

        return upper_temp_data, lower_temp_data

    def _extract_results_data_safely(
        self, value: dict[str, Any]
    ) -> tuple[dict[str, Any], dict[str, Any]]:
        """Safely extract upper and lower results data from a setpoint value.

        Args:
            value: Setpoint dictionary containing results data

        Returns:
            Tuple of (upper_results, lower_results) dictionaries
        """
        results_data_item_raw = value.get("results", {})
        results_data_item: dict[str, Any] = (
            results_data_item_raw if isinstance(results_data_item_raw, dict) else {}
        )

        if isinstance(results_data_item, dict):
            upper_results_raw: dict[str, Any] | float | str = results_data_item.get(
                "upper", {}
            )
            lower_results_raw: dict[str, Any] | float | str = results_data_item.get(
                "lower", {}
            )
            upper_results = (
                upper_results_raw if isinstance(upper_results_raw, dict) else {}
            )
            lower_results = (
                lower_results_raw if isinstance(lower_results_raw, dict) else {}
            )
        else:
            upper_results = {}
            lower_results = {}

        return upper_results, lower_results

    def _extract_conductivity_units(
        self,
        upper_temp_data: dict[str, Any],
        lower_temp_data: dict[str, Any],
        upper_results: dict[str, Any],
        lower_results: dict[str, Any],
    ) -> list[str]:
        """Extract units from conductivity data.

        Args:
            upper_temp_data: Upper temperature data dictionary
            lower_temp_data: Lower temperature data dictionary
            upper_results: Upper results data dictionary
            lower_results: Lower results data dictionary

        Returns:
            List of units [upper_temp_unit, lower_temp_unit, upper_result_unit, lower_result_unit]
        """
        upper_temp_unit = (
            upper_temp_data.get("unit") if isinstance(upper_temp_data, dict) else None
        )
        lower_temp_unit = (
            lower_temp_data.get("unit") if isinstance(lower_temp_data, dict) else None
        )
        upper_result_unit = (
            upper_results.get("unit") if isinstance(upper_results, dict) else None
        )
        lower_result_unit = (
            lower_results.get("unit") if isinstance(lower_results, dict) else None
        )

        return [
            upper_temp_unit if isinstance(upper_temp_unit, str) else "°C",
            lower_temp_unit if isinstance(lower_temp_unit, str) else "°C",
            upper_result_unit if isinstance(upper_result_unit, str) else "W/m·K",
            lower_result_unit if isinstance(lower_result_unit, str) else "W/m·K",
        ]

    def _extract_conductivity_data(self, metadata: FileMetadata) -> pa.Table:
        """Extract thermal conductivity data with optimized pre-allocation."""
        if "setpoints" not in metadata:
            error_msg = "No setpoints found in metadata"
            raise HFMDataExtractionError(
                error_msg,
                measurement_type=HFMType.CONDUCTIVITY.value,
            )

        setpoints = metadata["setpoints"]

        # Check if we have any setpoints with actual data (not just empty structures)
        valid_setpoints_with_data: list[tuple[str, dict[str, Any]]] = []
        for key, value in setpoints.items():
            if (
                isinstance(value, dict)
                and "temperature" in value
                and "results" in value
                and isinstance(value["temperature"], dict)
                and isinstance(value["results"], dict)
            ):
                temp_data = value["temperature"]
                results_data = value["results"]
                # Check if we have both upper and lower data with actual values
                upper_temp = temp_data.get("upper")
                lower_temp = temp_data.get("lower")
                upper_result = results_data.get("upper")
                lower_result = results_data.get("lower")

                if (
                    isinstance(upper_temp, dict)
                    and isinstance(lower_temp, dict)
                    and isinstance(upper_result, dict)
                    and isinstance(lower_result, dict)
                    and upper_temp.get("value") is not None
                    and lower_temp.get("value") is not None
                    and upper_result.get("value") is not None
                    and lower_result.get("value") is not None
                ):
                    valid_setpoints_with_data.append((key, value))

        num_rows = len(valid_setpoints_with_data)
        if num_rows == 0:
            error_msg = "No setpoints with valid conductivity data found"
            raise HFMDataExtractionError(
                error_msg,
                measurement_type=HFMType.CONDUCTIVITY.value,
            )

        # Use only valid setpoints for processing
        setpoints = dict(valid_setpoints_with_data)

        # Pre-allocate arrays for known size (much faster than list appends)
        setpoint_ids = np.empty(num_rows, dtype=np.int32)
        upper_temps = np.empty(num_rows, dtype=np.float64)
        lower_temps = np.empty(num_rows, dtype=np.float64)
        upper_conds = np.empty(num_rows, dtype=np.float64)
        lower_conds = np.empty(num_rows, dtype=np.float64)

        units: list[str] = []

        try:
            # Single-pass extraction with pre-allocated arrays
            for i, (key, value) in enumerate(setpoints.items()):
                setpoint_ids[i] = int(key.split("_")[1])

                # Extract temperature and results data using helper methods
                upper_temp_data, lower_temp_data = (
                    self._extract_temperature_data_safely(value)
                )
                upper_results, lower_results = self._extract_results_data_safely(value)

                # Extract temperature values
                upper_temps[i] = (
                    upper_temp_data.get("value", np.nan)
                    if isinstance(upper_temp_data, dict)
                    else np.nan
                )
                lower_temps[i] = (
                    lower_temp_data.get("value", np.nan)
                    if isinstance(lower_temp_data, dict)
                    else np.nan
                )

                # Extract conductivity values
                upper_conds[i] = (
                    upper_results.get("value", np.nan)
                    if isinstance(upper_results, dict)
                    else np.nan
                )
                lower_conds[i] = (
                    lower_results.get("value", np.nan)
                    if isinstance(lower_results, dict)
                    else np.nan
                )

                # Collect units from first valid entry
                if (
                    not units
                    and upper_temp_data
                    and lower_temp_data
                    and upper_results
                    and lower_results
                ):
                    units = self._extract_conductivity_units(
                        upper_temp_data, lower_temp_data, upper_results, lower_results
                    )

            # Direct PyArrow table creation (no transpose needed)
            table = pa.table(
                {
                    "setpoint": pa.array(setpoint_ids),
                    "upper_temperature": pa.array(upper_temps),
                    "lower_temperature": pa.array(lower_temps),
                    "upper_thermal_conductivity": pa.array(upper_conds),
                    "lower_thermal_conductivity": pa.array(lower_conds),
                }
            )

            # Add column metadata if units available
            if units:
                col_units = {
                    "upper_temperature": {"units": units[0]},
                    "lower_temperature": {"units": units[1]},
                    "upper_thermal_conductivity": {"units": units[2]},
                    "lower_thermal_conductivity": {"units": units[3]},
                }
                table = set_metadata(table, col_meta=col_units)

        except Exception as e:
            if isinstance(e, HFMDataExtractionError):
                raise
            error_msg = f"Failed to process conductivity data: {e}"
            raise HFMDataExtractionError(
                error_msg,
                measurement_type=HFMType.CONDUCTIVITY.value,
            ) from e
        else:
            return table

    def _extract_conductivity_setpoint(self, value: Any) -> dict[str, Any] | None:
        """Extract conductivity data from a single setpoint."""
        # Validate input and extract base structures
        temp_data, results_data = self._validate_and_extract_base_data(value)
        if temp_data is None or results_data is None:
            return None

        # Extract temperature data
        temp_values = self._extract_temperature_data(temp_data)
        if temp_values is None:
            return None

        # Extract conductivity data
        cond_values = self._extract_conductivity_results(results_data)
        if cond_values is None:
            return None

        # Combine and validate all values
        all_values = [*temp_values["values"], *cond_values["values"]]
        all_units = [*temp_values["units"], *cond_values["units"]]

        # Final validation
        if any(x is None for x in all_values) or not all(
            isinstance(x, (int, float)) for x in all_values
        ):
            return None

        return {"values": all_values, "units": all_units}

    def _validate_and_extract_base_data(
        self, value: Any
    ) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
        """Validate input and extract base temperature and results data."""
        if not isinstance(value, dict) or "temperature" not in value:
            return None, None

        temp_data = value["temperature"]
        if not isinstance(temp_data, dict):
            return None, None

        results_data = value.get("results", {})
        if not isinstance(results_data, dict):
            return None, None

        return temp_data, results_data

    def _extract_temperature_data(
        self, temp_data: dict[str, Any]
    ) -> dict[str, list[Any]] | None:
        """Extract temperature values and units."""
        upper_temp_data: Any = temp_data.get("upper", {})
        lower_temp_data: Any = temp_data.get("lower", {})

        if not isinstance(upper_temp_data, dict) or not isinstance(
            lower_temp_data, dict
        ):
            return None

        upper_temp = upper_temp_data.get("value")
        upper_temp_unit = upper_temp_data.get("unit")
        lower_temp = lower_temp_data.get("value")
        lower_temp_unit = lower_temp_data.get("unit")

        return {
            "values": [upper_temp, lower_temp],
            "units": [upper_temp_unit, lower_temp_unit],
        }

    def _extract_conductivity_results(
        self, results_data: dict[str, Any]
    ) -> dict[str, list[Any]] | None:
        """Extract conductivity values and units."""
        upper_results: Any = results_data.get("upper", {})
        lower_results: Any = results_data.get("lower", {})

        if not isinstance(upper_results, dict) or not isinstance(lower_results, dict):
            return None

        upper_cond = upper_results.get("value")
        upper_cond_unit = upper_results.get("unit")
        lower_cond = lower_results.get("value")
        lower_cond_unit = lower_results.get("unit")

        return {
            "values": [upper_cond, lower_cond],
            "units": [upper_cond_unit, lower_cond_unit],
        }

    def _extract_heat_capacity_data(self, metadata: FileMetadata) -> pa.Table:
        """Extract volumetric heat capacity data with optimized pre-allocation."""
        if "setpoints" not in metadata:
            error_msg = "No setpoints found in metadata"
            raise HFMDataExtractionError(
                error_msg,
                measurement_type=HFMType.VOLUMETRIC_HEAT_CAPACITY.value,
            )

        setpoints = metadata["setpoints"]

        # Filter valid setpoints with actual data first to get accurate count
        valid_setpoints = []
        for key, value in setpoints.items():
            if not isinstance(value, dict):
                continue
            required_keys = ["temperature_average", "volumetric_heat_capacity"]
            if all(k in value for k in required_keys):
                # Check if the data actually has values
                temp_avg_data = value.get("temperature_average", {})
                heat_cap_data = value.get("volumetric_heat_capacity", {})
                if (
                    isinstance(temp_avg_data, dict)
                    and isinstance(heat_cap_data, dict)
                    and temp_avg_data.get("value") is not None
                    and heat_cap_data.get("value") is not None
                ):
                    valid_setpoints.append((key, value))

        num_rows = len(valid_setpoints)
        if num_rows == 0:
            error_msg = "No setpoints with valid heat capacity data found"
            raise HFMDataExtractionError(
                error_msg,
                measurement_type=HFMType.VOLUMETRIC_HEAT_CAPACITY.value,
            )

        # Pre-allocate arrays for known size
        setpoint_ids = np.empty(num_rows, dtype=np.int32)
        avg_temps = np.empty(num_rows, dtype=np.float64)
        heat_caps = np.empty(num_rows, dtype=np.float64)

        units: list[str] = []

        try:
            # Single-pass extraction with pre-allocated arrays
            for i, (key, value) in enumerate(valid_setpoints):
                setpoint_ids[i] = int(key.split("_")[1])

                # Extract temperature average with direct access
                temp_avg_data = value["temperature_average"]
                avg_temps[i] = (
                    temp_avg_data.get("value", np.nan)
                    if isinstance(temp_avg_data, dict)
                    else np.nan
                )

                # Extract heat capacity with direct access
                heat_cap_data = value["volumetric_heat_capacity"]
                heat_caps[i] = (
                    heat_cap_data.get("value", np.nan)
                    if isinstance(heat_cap_data, dict)
                    else np.nan
                )

                # Collect units from first valid entry
                if not units and temp_avg_data and heat_cap_data:
                    temp_unit = (
                        temp_avg_data.get("unit")
                        if isinstance(temp_avg_data, dict)
                        else None
                    )
                    heat_cap_unit = (
                        heat_cap_data.get("unit")
                        if isinstance(heat_cap_data, dict)
                        else None
                    )
                    units = [
                        temp_unit if isinstance(temp_unit, str) else "°C",
                        heat_cap_unit if isinstance(heat_cap_unit, str) else "J/m³·K",
                    ]

            # Direct PyArrow table creation
            table = pa.table(
                {
                    "setpoint": pa.array(setpoint_ids),
                    "average_temperature": pa.array(avg_temps),
                    "volumetric_heat_capacity": pa.array(heat_caps),
                }
            )

            # Add column metadata if units available
            if units:
                col_units = {
                    "average_temperature": {"units": units[0]},
                    "volumetric_heat_capacity": {"units": units[1]},
                }
                table = set_metadata(table, col_meta=col_units)

        except Exception as e:
            if isinstance(e, HFMDataExtractionError):
                raise
            error_msg = f"Failed to process heat capacity data: {e}"
            raise HFMDataExtractionError(
                error_msg,
                measurement_type=HFMType.VOLUMETRIC_HEAT_CAPACITY.value,
            ) from e
        else:
            return table

    def _create_table(
        self,
        data: list[list[Any]],
        schema: pa.Schema,
        col_units: dict[str, dict[str, Any]],
    ) -> pa.Table:
        """Create PyArrow table from data (legacy method - now replaced by direct table creation).

        Args:
            data: List of data rows
            schema: PyArrow schema
            col_units: Column unit metadata

        Returns:
            PyArrow table with metadata
        """
        if not data:
            error_msg = "No data to create table"
            raise HFMDataExtractionError(error_msg)

        try:
            # Transpose data to match schema
            trans_data = np.transpose(data)
            arrays = [pa.array(trans_data[i]) for i in range(len(trans_data))]

            # Create PyArrow table from arrays and schema
            table = pa.Table.from_arrays(arrays, schema=schema)

            # Add column metadata
            if col_units:
                table = set_metadata(table, col_meta=col_units)

        except Exception as e:
            error_msg = f"Failed to create PyArrow table: {e}"
            raise HFMDataExtractionError(error_msg) from e
        else:
            return table

Methods:

__init__(config=None)

Initialize data extractor.

Parameters:

Name Type Description Default
config dict[str, Any] | None

Optional configuration overrides

None
Source code in src/pyhfm/extractors/data_extractor.py
def __init__(self, config: dict[str, Any] | None = None) -> None:
    """Initialize data extractor.

    Args:
        config: Optional configuration overrides
    """
    self.config = DEFAULT_COLUMN_CONFIG
    if config:
        # Apply configuration overrides
        for key, value in config.items():
            if hasattr(self.config, key):
                setattr(self.config, key, value)

extract_data(metadata)

Extract data from metadata and return PyArrow table.

Parameters:

Name Type Description Default
metadata FileMetadata

HFM metadata dictionary

required

Returns:

Type Description
Table

PyArrow table with measurement data

Raises:

Type Description
HFMDataExtractionError

If data extraction fails

Source code in src/pyhfm/extractors/data_extractor.py
def extract_data(self, metadata: FileMetadata) -> pa.Table:
    """Extract data from metadata and return PyArrow table.

    Args:
        metadata: HFM metadata dictionary

    Returns:
        PyArrow table with measurement data

    Raises:
        HFMDataExtractionError: If data extraction fails
    """
    measurement_type = metadata.get("type")
    if not measurement_type:
        error_msg = "Missing measurement type in metadata"
        raise HFMDataExtractionError(
            error_msg,
            measurement_type=measurement_type,
        )

    try:
        if measurement_type == HFMType.CONDUCTIVITY.value:
            return self._extract_conductivity_data(metadata)
        if measurement_type == HFMType.VOLUMETRIC_HEAT_CAPACITY.value:
            return self._extract_heat_capacity_data(metadata)

        # Handle unsupported measurement type
        self._raise_unsupported_type_error(measurement_type)
    except Exception as e:
        if isinstance(e, HFMDataExtractionError):
            raise
        error_msg = f"Failed to extract data: {e}"
        raise HFMDataExtractionError(
            error_msg,
            measurement_type=measurement_type,
        ) from e

API Module

Loaders

pyhfm.api.loaders

Main API for loading HFM data files.

Classes

Functions:

read_hfm(file_path, *, return_metadata=False, config=None)

read_hfm(
    file_path: str | Path,
    *,
    return_metadata: Literal[False] = False,
    config: dict[str, Any] | None = None,
) -> pa.Table
read_hfm(
    file_path: str | Path,
    *,
    return_metadata: Literal[True],
    config: dict[str, Any] | None = None,
) -> tuple[FileMetadata, pa.Table]

Read and parse an HFM data file.

This is the main entry point for reading Heat Flow Meter (HFM) data files. The function returns a PyArrow table with embedded metadata by default, or optionally returns a tuple of (metadata, table) for more detailed access.

Parameters:

Name Type Description Default
file_path str | Path

Path to the HFM file (.tst format)

required
return_metadata bool

If True, return (metadata, table) tuple instead of just table

False
config dict[str, Any] | None

Optional configuration overrides for parsing

None

Returns:

Type Description
Table | tuple[FileMetadata, Table]

PyArrow table with embedded metadata, or tuple of (metadata, table)

Table | tuple[FileMetadata, Table]

if return_metadata=True

Raises:

Type Description
HFMFileError

If file cannot be read or doesn't exist

HFMParsingError

If file parsing fails

HFMUnsupportedFormatError

If file format is not supported

HFMValidationError

If data validation fails

Examples:

Basic usage:

>>> import polars as pl
>>> table = read_hfm("sample.tst")
>>> print(table.schema)
>>> print(pl.from_arrow(table))

Access metadata separately:

>>> metadata, table = read_hfm("sample.tst", return_metadata=True)
>>> print(metadata["sample_id"])
>>> print(metadata["type"])

Custom configuration:

>>> config = {"default_encoding": "utf-8"}
>>> table = read_hfm("sample.tst", config=config)
Source code in src/pyhfm/api/loaders.py
def read_hfm(
    file_path: str | Path,
    *,
    return_metadata: bool = False,
    config: dict[str, Any] | None = None,
) -> pa.Table | tuple[FileMetadata, pa.Table]:
    """Read and parse an HFM data file.

    This is the main entry point for reading Heat Flow Meter (HFM) data files.
    The function returns a PyArrow table with embedded metadata by default, or
    optionally returns a tuple of (metadata, table) for more detailed access.

    Args:
        file_path: Path to the HFM file (.tst format)
        return_metadata: If True, return (metadata, table) tuple instead of just table
        config: Optional configuration overrides for parsing

    Returns:
        PyArrow table with embedded metadata, or tuple of (metadata, table)
        if return_metadata=True

    Raises:
        HFMFileError: If file cannot be read or doesn't exist
        HFMParsingError: If file parsing fails
        HFMUnsupportedFormatError: If file format is not supported
        HFMValidationError: If data validation fails

    Examples:
        Basic usage:
        >>> import polars as pl
        >>> table = read_hfm("sample.tst")
        >>> print(table.schema)
        >>> print(pl.from_arrow(table))

        Access metadata separately:
        >>> metadata, table = read_hfm("sample.tst", return_metadata=True)
        >>> print(metadata["sample_id"])
        >>> print(metadata["type"])

        Custom configuration:
        >>> config = {"default_encoding": "utf-8"}
        >>> table = read_hfm("sample.tst", config=config)
    """
    try:
        # Initialize parser with optional config
        parser = HFMParser(config)

        # Parse the file
        table = parser.parse_file(file_path)

        if return_metadata:
            # Extract metadata from table
            table_metadata = table.schema.metadata
            if table_metadata and b"file_metadata" in table_metadata:
                # Deserialize the metadata from JSON bytes
                file_metadata_bytes = table_metadata[b"file_metadata"]
                file_metadata = json.loads(file_metadata_bytes.decode("utf-8"))
                return file_metadata, table
            # Fallback - re-parse to get metadata
            metadata_parser = HFMParser(config)
            metadata_table = metadata_parser.parse_file(file_path)
            metadata_dict = metadata_table.schema.metadata
            if metadata_dict and b"file_metadata" in metadata_dict:
                file_metadata_bytes = metadata_dict[b"file_metadata"]
                file_metadata = json.loads(file_metadata_bytes.decode("utf-8"))
                return file_metadata, table
            return {}, table

    except HFMError:
        # Re-raise HFM-specific errors as-is
        raise
    except Exception as e:
        # Wrap unexpected errors
        error_msg = f"Unexpected error reading HFM file: {e}"
        raise HFMError(error_msg, str(file_path)) from e
    else:
        return table

main()

Command-line interface for reading HFM files.

Usage

pyhfm [options]

Source code in src/pyhfm/api/loaders.py
def main() -> None:
    """Command-line interface for reading HFM files.

    Usage:
        pyhfm <file_path> [options]
    """
    parser = argparse.ArgumentParser(description="Read and parse HFM data files")
    parser.add_argument("file_path", help="Path to HFM file")
    parser.add_argument(
        "--output", "-o", help="Output file path (default: print to stdout)"
    )
    parser.add_argument(
        "--format",
        "-f",
        choices=["csv", "parquet", "json"],
        default="csv",
        help="Output format (default: csv)",
    )
    parser.add_argument(
        "--metadata", "-m", action="store_true", help="Also output metadata information"
    )
    parser.add_argument(
        "--encoding", help="File encoding override (default: auto-detect)"
    )

    try:
        args = parser.parse_args()

        # Prepare config
        config = {}
        if args.encoding:
            config["default_encoding"] = args.encoding

        # Read the file
        metadata: dict[str, Any] | None = None
        if args.metadata:
            file_metadata, table = read_hfm(
                args.file_path, return_metadata=True, config=config if config else None
            )
            metadata = cast("dict[str, Any]", file_metadata)
        else:
            table = read_hfm(args.file_path, config=config if config else None)

        # Handle output
        _handle_output(args, table, metadata)

    except HFMError as e:
        error_msg = f"Error: {e}"
        print(error_msg, file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        error_msg = f"Unexpected error: {e}"
        print(error_msg, file=sys.stderr)
        sys.exit(1)

Exceptions

pyhfm.exceptions

Custom exceptions for HFM data processing.

Classes

HFMError

Bases: Exception

Base exception for all HFM-related errors.

Source code in src/pyhfm/exceptions.py
class HFMError(Exception):
    """Base exception for all HFM-related errors."""

    def __init__(self, message: str, file_path: str | None = None) -> None:
        """Initialize HFM error.

        Args:
            message: Error description
            file_path: Optional path to file that caused the error
        """
        self.message = message
        self.file_path = file_path
        super().__init__(self._format_message())

    def _format_message(self) -> str:
        """Format error message with optional file path."""
        if self.file_path:
            return f"{self.message} (file: {self.file_path})"
        return self.message
Methods:
__init__(message, file_path=None)

Initialize HFM error.

Parameters:

Name Type Description Default
message str

Error description

required
file_path str | None

Optional path to file that caused the error

None
Source code in src/pyhfm/exceptions.py
def __init__(self, message: str, file_path: str | None = None) -> None:
    """Initialize HFM error.

    Args:
        message: Error description
        file_path: Optional path to file that caused the error
    """
    self.message = message
    self.file_path = file_path
    super().__init__(self._format_message())

HFMValidationWarning

Bases: UserWarning

Warning for recoverable inconsistencies found while parsing HFM files.

Emitted (via warnings.warn) when a file can still be parsed but its contents look suspicious — e.g. the number of parsed setpoints does not match the declared Number of Setpoints: header, or setpoint numbering restarts mid-file because an interrupted test was resumed.

Source code in src/pyhfm/exceptions.py
class HFMValidationWarning(UserWarning):
    """Warning for recoverable inconsistencies found while parsing HFM files.

    Emitted (via ``warnings.warn``) when a file can still be parsed but its
    contents look suspicious — e.g. the number of parsed setpoints does not
    match the declared ``Number of Setpoints:`` header, or setpoint numbering
    restarts mid-file because an interrupted test was resumed.
    """

HFMParsingError

Bases: HFMError

Raised when HFM file parsing fails.

Source code in src/pyhfm/exceptions.py
class HFMParsingError(HFMError):
    """Raised when HFM file parsing fails."""

    def __init__(
        self,
        message: str,
        file_path: str | None = None,
        line_number: int | None = None,
    ) -> None:
        """Initialize parsing error.

        Args:
            message: Error description
            file_path: Optional path to file that caused the error
            line_number: Optional line number where error occurred
        """
        self.line_number = line_number
        super().__init__(message, file_path)

    def _format_message(self) -> str:
        """Format error message with optional file path and line number."""
        parts = [self.message]
        if self.file_path:
            parts.append(f"file: {self.file_path}")
        if self.line_number is not None:
            parts.append(f"line: {self.line_number}")

        if len(parts) > 1:
            return f"{parts[0]} ({', '.join(parts[1:])})"
        return parts[0]
Methods:
__init__(message, file_path=None, line_number=None)

Initialize parsing error.

Parameters:

Name Type Description Default
message str

Error description

required
file_path str | None

Optional path to file that caused the error

None
line_number int | None

Optional line number where error occurred

None
Source code in src/pyhfm/exceptions.py
def __init__(
    self,
    message: str,
    file_path: str | None = None,
    line_number: int | None = None,
) -> None:
    """Initialize parsing error.

    Args:
        message: Error description
        file_path: Optional path to file that caused the error
        line_number: Optional line number where error occurred
    """
    self.line_number = line_number
    super().__init__(message, file_path)

HFMValidationError

Bases: HFMError

Raised when HFM data validation fails.

Source code in src/pyhfm/exceptions.py
class HFMValidationError(HFMError):
    """Raised when HFM data validation fails."""

    def __init__(
        self,
        message: str,
        file_path: str | None = None,
        field_name: str | None = None,
        invalid_value: str | float | int | None = None,
    ) -> None:
        """Initialize validation error.

        Args:
            message: Error description
            file_path: Optional path to file that caused the error
            field_name: Optional name of the invalid field
            invalid_value: Optional invalid value that caused the error
        """
        self.field_name = field_name
        self.invalid_value = invalid_value
        super().__init__(message, file_path)

    def _format_message(self) -> str:
        """Format error message with optional details."""
        parts = [self.message]
        if self.field_name:
            parts.append(f"field: {self.field_name}")
        if self.invalid_value is not None:
            parts.append(f"value: {self.invalid_value}")
        if self.file_path:
            parts.append(f"file: {self.file_path}")

        if len(parts) > 1:
            return f"{parts[0]} ({', '.join(parts[1:])})"
        return parts[0]
Methods:
__init__(message, file_path=None, field_name=None, invalid_value=None)

Initialize validation error.

Parameters:

Name Type Description Default
message str

Error description

required
file_path str | None

Optional path to file that caused the error

None
field_name str | None

Optional name of the invalid field

None
invalid_value str | float | int | None

Optional invalid value that caused the error

None
Source code in src/pyhfm/exceptions.py
def __init__(
    self,
    message: str,
    file_path: str | None = None,
    field_name: str | None = None,
    invalid_value: str | float | int | None = None,
) -> None:
    """Initialize validation error.

    Args:
        message: Error description
        file_path: Optional path to file that caused the error
        field_name: Optional name of the invalid field
        invalid_value: Optional invalid value that caused the error
    """
    self.field_name = field_name
    self.invalid_value = invalid_value
    super().__init__(message, file_path)

HFMMetadataError

Bases: HFMError

Raised when metadata extraction fails.

Source code in src/pyhfm/exceptions.py
class HFMMetadataError(HFMError):
    """Raised when metadata extraction fails."""

    def __init__(
        self,
        message: str,
        file_path: str | None = None,
        missing_fields: list[str] | None = None,
    ) -> None:
        """Initialize metadata error.

        Args:
            message: Error description
            file_path: Optional path to file that caused the error
            missing_fields: Optional list of missing required fields
        """
        self.missing_fields = missing_fields or []
        super().__init__(message, file_path)

    def _format_message(self) -> str:
        """Format error message with missing fields."""
        parts = [self.message]
        if self.missing_fields:
            parts.append(f"missing fields: {', '.join(self.missing_fields)}")
        if self.file_path:
            parts.append(f"file: {self.file_path}")

        if len(parts) > 1:
            return f"{parts[0]} ({', '.join(parts[1:])})"
        return parts[0]
Methods:
__init__(message, file_path=None, missing_fields=None)

Initialize metadata error.

Parameters:

Name Type Description Default
message str

Error description

required
file_path str | None

Optional path to file that caused the error

None
missing_fields list[str] | None

Optional list of missing required fields

None
Source code in src/pyhfm/exceptions.py
def __init__(
    self,
    message: str,
    file_path: str | None = None,
    missing_fields: list[str] | None = None,
) -> None:
    """Initialize metadata error.

    Args:
        message: Error description
        file_path: Optional path to file that caused the error
        missing_fields: Optional list of missing required fields
    """
    self.missing_fields = missing_fields or []
    super().__init__(message, file_path)

HFMDataExtractionError

Bases: HFMError

Raised when data extraction from metadata fails.

Source code in src/pyhfm/exceptions.py
class HFMDataExtractionError(HFMError):
    """Raised when data extraction from metadata fails."""

    def __init__(
        self,
        message: str,
        file_path: str | None = None,
        measurement_type: str | None = None,
        setpoint: int | None = None,
    ) -> None:
        """Initialize data extraction error.

        Args:
            message: Error description
            file_path: Optional path to file that caused the error
            measurement_type: Optional measurement type (conductivity, heat_capacity)
            setpoint: Optional setpoint number that caused the error
        """
        self.measurement_type = measurement_type
        self.setpoint = setpoint
        super().__init__(message, file_path)

    def _format_message(self) -> str:
        """Format error message with extraction details."""
        parts = [self.message]
        if self.measurement_type:
            parts.append(f"type: {self.measurement_type}")
        if self.setpoint is not None:
            parts.append(f"setpoint: {self.setpoint}")
        if self.file_path:
            parts.append(f"file: {self.file_path}")

        if len(parts) > 1:
            return f"{parts[0]} ({', '.join(parts[1:])})"
        return parts[0]
Methods:
__init__(message, file_path=None, measurement_type=None, setpoint=None)

Initialize data extraction error.

Parameters:

Name Type Description Default
message str

Error description

required
file_path str | None

Optional path to file that caused the error

None
measurement_type str | None

Optional measurement type (conductivity, heat_capacity)

None
setpoint int | None

Optional setpoint number that caused the error

None
Source code in src/pyhfm/exceptions.py
def __init__(
    self,
    message: str,
    file_path: str | None = None,
    measurement_type: str | None = None,
    setpoint: int | None = None,
) -> None:
    """Initialize data extraction error.

    Args:
        message: Error description
        file_path: Optional path to file that caused the error
        measurement_type: Optional measurement type (conductivity, heat_capacity)
        setpoint: Optional setpoint number that caused the error
    """
    self.measurement_type = measurement_type
    self.setpoint = setpoint
    super().__init__(message, file_path)

HFMFileError

Bases: HFMError

Raised when file operations fail.

Source code in src/pyhfm/exceptions.py
class HFMFileError(HFMError):
    """Raised when file operations fail."""

    def __init__(
        self,
        message: str,
        file_path: str | None = None,
        operation: str | None = None,
    ) -> None:
        """Initialize file error.

        Args:
            message: Error description
            file_path: Optional path to file that caused the error
            operation: Optional operation that failed (read, write, detect_encoding)
        """
        self.operation = operation
        super().__init__(message, file_path)

    def _format_message(self) -> str:
        """Format error message with operation details."""
        parts = [self.message]
        if self.operation:
            parts.append(f"operation: {self.operation}")
        if self.file_path:
            parts.append(f"file: {self.file_path}")

        if len(parts) > 1:
            return f"{parts[0]} ({', '.join(parts[1:])})"
        return parts[0]
Methods:
__init__(message, file_path=None, operation=None)

Initialize file error.

Parameters:

Name Type Description Default
message str

Error description

required
file_path str | None

Optional path to file that caused the error

None
operation str | None

Optional operation that failed (read, write, detect_encoding)

None
Source code in src/pyhfm/exceptions.py
def __init__(
    self,
    message: str,
    file_path: str | None = None,
    operation: str | None = None,
) -> None:
    """Initialize file error.

    Args:
        message: Error description
        file_path: Optional path to file that caused the error
        operation: Optional operation that failed (read, write, detect_encoding)
    """
    self.operation = operation
    super().__init__(message, file_path)

HFMUnsupportedFormatError

Bases: HFMError

Raised when file format is not supported.

Source code in src/pyhfm/exceptions.py
class HFMUnsupportedFormatError(HFMError):
    """Raised when file format is not supported."""

    def __init__(
        self,
        message: str,
        file_path: str | None = None,
        detected_format: str | None = None,
        supported_formats: list[str] | None = None,
    ) -> None:
        """Initialize unsupported format error.

        Args:
            message: Error description
            file_path: Optional path to file that caused the error
            detected_format: Optional detected file format
            supported_formats: Optional list of supported formats
        """
        self.detected_format = detected_format
        self.supported_formats = supported_formats or []
        super().__init__(message, file_path)

    def _format_message(self) -> str:
        """Format error message with format details."""
        parts = [self.message]
        if self.detected_format:
            parts.append(f"detected: {self.detected_format}")
        if self.supported_formats:
            parts.append(f"supported: {', '.join(self.supported_formats)}")
        if self.file_path:
            parts.append(f"file: {self.file_path}")

        if len(parts) > 1:
            return f"{parts[0]} ({', '.join(parts[1:])})"
        return parts[0]
Methods:
__init__(message, file_path=None, detected_format=None, supported_formats=None)

Initialize unsupported format error.

Parameters:

Name Type Description Default
message str

Error description

required
file_path str | None

Optional path to file that caused the error

None
detected_format str | None

Optional detected file format

None
supported_formats list[str] | None

Optional list of supported formats

None
Source code in src/pyhfm/exceptions.py
def __init__(
    self,
    message: str,
    file_path: str | None = None,
    detected_format: str | None = None,
    supported_formats: list[str] | None = None,
) -> None:
    """Initialize unsupported format error.

    Args:
        message: Error description
        file_path: Optional path to file that caused the error
        detected_format: Optional detected file format
        supported_formats: Optional list of supported formats
    """
    self.detected_format = detected_format
    self.supported_formats = supported_formats or []
    super().__init__(message, file_path)

Constants and Configuration

pyhfm.constants

Constants and configuration for HFM data processing.

Classes

HFMType

Bases: Enum

HFM measurement types.

Source code in src/pyhfm/constants.py
class HFMType(Enum):
    """HFM measurement types."""

    CONDUCTIVITY = "conductivity"
    VOLUMETRIC_HEAT_CAPACITY = "volumetric_heat_capacity"

FileMetadata

Bases: TypedDict

Structured metadata for HFM files.

Source code in src/pyhfm/constants.py
class FileMetadata(TypedDict, total=False):
    """Structured metadata for HFM files."""

    # Core identification
    sample_id: str
    type: str
    date_performed: str

    # Physical properties
    thickness: dict[str, float | str] | float | str
    number_of_transducers: int
    number_of_setpoints: int

    # Calibration information
    calibration: dict[str, str | dict[str, float]]

    # Comments and notes
    comment: str | list[str]

    # Setpoint data
    setpoints: dict[str, dict[str, float | str | dict[str, float | str]]]

    # File information
    file_hash: dict[str, str]

TemperatureData

Bases: TypedDict

Temperature measurement data structure.

Source code in src/pyhfm/constants.py
class TemperatureData(TypedDict):
    """Temperature measurement data structure."""

    value: float
    unit: str

CalibrationData

Bases: TypedDict

Calibration data structure.

Source code in src/pyhfm/constants.py
class CalibrationData(TypedDict):
    """Calibration data structure."""

    value: float
    unit: str

ResultsData

Bases: TypedDict

Results data structure.

Source code in src/pyhfm/constants.py
class ResultsData(TypedDict):
    """Results data structure."""

    value: float
    unit: str

ThermalEquilibriumData

Bases: TypedDict

Thermal equilibrium criteria data.

Source code in src/pyhfm/constants.py
class ThermalEquilibriumData(TypedDict, total=False):
    """Thermal equilibrium criteria data."""

    temperature: float
    between_block: float
    percent_change: float
    min_number_of_blocks: float
    calculation_blocks: float

SetpointData

Bases: TypedDict

Complete setpoint data structure.

Source code in src/pyhfm/constants.py
class SetpointData(TypedDict, total=False):
    """Complete setpoint data structure."""

    instrument_setpoint_number: int
    date_performed: str
    setpoint_temperature: dict[str, TemperatureData]
    temperature: dict[str, TemperatureData]
    calibration: dict[str, CalibrationData]
    results: dict[str, ResultsData]
    thermal_equilibrium: ThermalEquilibriumData
    temperature_average: TemperatureData
    volumetric_heat_capacity: dict[str, float | str]

CompiledPatterns dataclass

Pre-compiled regex patterns for maximum efficiency.

Source code in src/pyhfm/constants.py
@dataclass(frozen=True)
class CompiledPatterns:
    """Pre-compiled regex patterns for maximum efficiency."""

    value_pattern: re.Pattern = field(default_factory=lambda: re.compile(r"-?\d+\.\d+"))
    unit_pattern: re.Pattern = field(default_factory=lambda: re.compile(r"[a-zA-Z]+"))
    unicode_unit_pattern: re.Pattern = field(
        default_factory=lambda: re.compile(r"[^\x00-\x7f]+[a-zA-Z]+")
    )
    unit_ratio_pattern: re.Pattern = field(
        default_factory=lambda: re.compile(r"[a-zA-Z]/[a-zA-Z]+")
    )
    setpoint_pattern: re.Pattern = field(
        default_factory=lambda: re.compile(r"setpoint\s+(\d+)")
    )
    date_pattern: re.Pattern = field(
        default_factory=lambda: re.compile(r"^\w+, \w+ \d+, \d+, Time \d+:\d+$")
    )

HFMParsingConfig dataclass

Configuration for HFM file parsing.

Source code in src/pyhfm/constants.py
@dataclass(frozen=True)
class HFMParsingConfig:
    """Configuration for HFM file parsing."""

    # Default encoding for HFM files
    default_encoding: str = "utf-16le"

    # Supported file extensions
    supported_extensions: tuple[str, ...] = (".tst",)

    # Date format patterns
    date_format: str = "%A, %B %d, %Y, Time %H:%M"

    # Pre-compiled regex patterns
    patterns: CompiledPatterns = field(default_factory=CompiledPatterns)

    # Default units for specific measurements
    default_calibration_unit: str = "µV/W"

ColumnConfig dataclass

Configuration for data table columns.

Source code in src/pyhfm/constants.py
@dataclass
class ColumnConfig:
    """Configuration for data table columns."""

    # Conductivity measurement columns
    conductivity_schema: dict[str, str] | None = None

    # Heat capacity measurement columns
    heat_capacity_schema: dict[str, str] | None = None

    def __post_init__(self) -> None:
        """Initialize default column schemas."""
        if self.conductivity_schema is None:
            self.conductivity_schema = {
                "setpoint": "int32",
                "upper_temperature": "float64",
                "lower_temperature": "float64",
                "upper_thermal_conductivity": "float64",
                "lower_thermal_conductivity": "float64",
            }

        if self.heat_capacity_schema is None:
            self.heat_capacity_schema = {
                "setpoint": "int32",
                "average_temperature": "float64",
                "volumetric_heat_capacity": "float64",
            }
Methods:
__post_init__()

Initialize default column schemas.

Source code in src/pyhfm/constants.py
def __post_init__(self) -> None:
    """Initialize default column schemas."""
    if self.conductivity_schema is None:
        self.conductivity_schema = {
            "setpoint": "int32",
            "upper_temperature": "float64",
            "lower_temperature": "float64",
            "upper_thermal_conductivity": "float64",
            "lower_thermal_conductivity": "float64",
        }

    if self.heat_capacity_schema is None:
        self.heat_capacity_schema = {
            "setpoint": "int32",
            "average_temperature": "float64",
            "volumetric_heat_capacity": "float64",
        }

ValidationConfig dataclass

Configuration for data validation.

Source code in src/pyhfm/constants.py
@dataclass(frozen=True)
class ValidationConfig:
    """Configuration for data validation."""

    # Temperature validation (in Kelvin)
    min_temperature: float = 0.0
    max_temperature: float = 2000.0

    # Conductivity validation (W/m·K)
    min_conductivity: float = 0.0
    max_conductivity: float = 1000.0

    # Heat capacity validation (J/m³·K)
    min_heat_capacity: float = 0.0
    max_heat_capacity: float = 1e7

    # Required metadata fields
    required_metadata: tuple[str, ...] = (
        "sample_id",
        "type",
        "file_hash",
    )

    # Optional but recommended metadata fields
    recommended_metadata: tuple[str, ...] = (
        "date_performed",
        "thickness",
        "calibration",
        "setpoints",
    )

Utilities

pyhfm.utils

Utility functions to replace labetl dependencies.

Functions:

detect_encoding(file_path)

Detect the encoding of a text file.

Parameters:

Name Type Description Default
file_path str

Path to the file to analyze

required

Returns:

Type Description
str

Detected encoding name (e.g., "utf-8", "ascii", "iso-8859-1")

str

Returns "utf-8" as fallback if detection fails

Source code in src/pyhfm/utils.py
def detect_encoding(file_path: str) -> str:
    """Detect the encoding of a text file.

    Args:
        file_path: Path to the file to analyze

    Returns:
        Detected encoding name (e.g., "utf-8", "ascii", "iso-8859-1")
        Returns "utf-8" as fallback if detection fails
    """
    try:
        with Path(file_path).open("rb") as f:
            # Read a sample of the file for encoding detection
            raw_data = f.read(8192)  # Read first 8KB

        if not raw_data:
            # Empty file, default to utf-8
            return "utf-8"

        result = chardet.detect(raw_data)

        if result and result["encoding"]:
            confidence = result.get("confidence", 0)
            # Only trust high-confidence detections
            if confidence > 0.7:
                encoding = result["encoding"]
                if isinstance(encoding, str):
                    return encoding.lower()

    except Exception:
        # If anything goes wrong, fall back to utf-8
        # We intentionally ignore exceptions here as encoding detection
        # should be best-effort with graceful fallback
        return "utf-8"

    # Fallback to utf-8 if confidence is low or detection failed
    return "utf-8"

get_hash(file_path)

Calculate SHA-256 hash of a file.

Parameters:

Name Type Description Default
file_path str

Path to the file to hash

required

Returns:

Type Description
str

Hexadecimal SHA-256 hash string

Raises:

Type Description
OSError

If file cannot be read

Source code in src/pyhfm/utils.py
def get_hash(file_path: str) -> str:
    """Calculate SHA-256 hash of a file.

    Args:
        file_path: Path to the file to hash

    Returns:
        Hexadecimal SHA-256 hash string

    Raises:
        OSError: If file cannot be read
    """
    sha256_hash = hashlib.sha256()

    with Path(file_path).open("rb") as f:
        # Read file in chunks to handle large files efficiently
        for chunk in iter(lambda: f.read(4096), b""):
            sha256_hash.update(chunk)

    return sha256_hash.hexdigest()

set_metadata(table, tbl_meta=None, col_meta=None)

Set metadata on a PyArrow table.

Parameters:

Name Type Description Default
table Table

PyArrow table to add metadata to

required
tbl_meta dict[str, Any] | None

Table-level metadata to add

None
col_meta dict[str, Any] | None

Column-level metadata to add (column name -> metadata dict)

None

Returns:

Type Description
Table

New PyArrow table with metadata attached

Source code in src/pyhfm/utils.py
def set_metadata(
    table: pa.Table,
    tbl_meta: dict[str, Any] | None = None,
    col_meta: dict[str, Any] | None = None,
) -> pa.Table:
    """Set metadata on a PyArrow table.

    Args:
        table: PyArrow table to add metadata to
        tbl_meta: Table-level metadata to add
        col_meta: Column-level metadata to add (column name -> metadata dict)

    Returns:
        New PyArrow table with metadata attached
    """
    # Start with existing metadata
    new_schema = table.schema

    # Add table-level metadata
    if tbl_meta:
        # Convert to JSON bytes as required by PyArrow
        metadata = {k: json.dumps(v).encode() for k, v in tbl_meta.items()}
        new_schema = new_schema.with_metadata(metadata)

    # Add column-level metadata
    if col_meta:
        fields = []
        for field in new_schema:
            field_name = field.name
            if field_name in col_meta:
                # Convert column metadata to JSON bytes
                col_metadata: dict[str | bytes, str | bytes] = {
                    str(k): json.dumps(v).encode()
                    for k, v in col_meta[field_name].items()
                }
                new_field = field.with_metadata(col_metadata)
            else:
                new_field = field
            fields.append(new_field)
        new_schema = pa.schema(
            fields,
            metadata=cast("dict[bytes | str, bytes | str] | None", new_schema.metadata),
        )

    # Return new table with updated schema
    return table.cast(new_schema)