Coverage for src / tracekit / loaders / binary.py: 100%

15 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-11 23:04 +0000

1"""Binary file loader for raw signal data. 

2 

3Loads raw binary files containing signal data with user-specified format. 

4""" 

5 

6from __future__ import annotations 

7 

8from pathlib import Path 

9from typing import TYPE_CHECKING, Any 

10 

11import numpy as np 

12 

13from tracekit.core.types import TraceMetadata, WaveformTrace 

14 

15if TYPE_CHECKING: 

16 from os import PathLike 

17 

18 

19def load_binary( 

20 path: str | PathLike[str], 

21 *, 

22 dtype: str | np.dtype[Any] = "float64", 

23 sample_rate: float = 1.0, 

24 channels: int = 1, 

25 channel: int = 0, 

26 offset: int = 0, 

27 count: int = -1, 

28) -> WaveformTrace: 

29 """Load raw binary file as waveform trace. 

30 

31 Args: 

32 path: Path to the binary file. 

33 dtype: NumPy dtype for the data (default: float64). 

34 sample_rate: Sample rate in Hz. 

35 channels: Number of interleaved channels. 

36 channel: Channel index to load (0-based). 

37 offset: Number of samples to skip from start. 

38 count: Number of samples to read (-1 for all). 

39 

40 Returns: 

41 WaveformTrace containing the loaded data. 

42 

43 Example: 

44 >>> from tracekit.loaders.binary import load_binary 

45 >>> trace = load_binary("signal.bin", dtype="int16", sample_rate=1e6) 

46 """ 

47 path = Path(path) 

48 

49 # Load raw data 

50 data = np.fromfile(path, dtype=dtype, count=count, offset=offset * np.dtype(dtype).itemsize) 

51 

52 # Handle multi-channel data 

53 if channels > 1: 

54 # Reshape and select channel 

55 samples_per_channel = len(data) // channels 

56 data = data[: samples_per_channel * channels].reshape(-1, channels) 

57 data = data[:, channel] 

58 

59 # Create metadata 

60 metadata = TraceMetadata( 

61 sample_rate=sample_rate, 

62 source_file=str(path), 

63 channel_name=f"Channel {channel}", 

64 ) 

65 

66 return WaveformTrace(data=data.astype(np.float64), metadata=metadata) 

67 

68 

69__all__ = ["load_binary"]