Coverage for tcvx21/file_io/matlab_file_reader_m.py: 80%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

15 statements  

1""" 

2Functions for reading MATLAB data '.mat' files 

3 

4recomended usage is read_struct_from_file(filepath) 

5""" 

6import numpy as np 

7from scipy.io import loadmat 

8from pathlib import Path 

9 

10 

11def read_struct_from_file(filepath: Path, struct_name=None) -> dict: 

12 """ 

13 Reads a struct called struct_name from a file at filepath 

14 """ 

15 assert filepath.exists(), f"File not found {filepath.absolute()}" 

16 

17 if struct_name is None: 

18 mat_file = loadmat(filepath, simplify_cells=True) 

19 struct_names = [key for key in mat_file if key not in ['__header__', '__version__', '__globals__']] 

20 

21 if len(struct_names) > 1: 

22 raise RuntimeError(f"Multiple structs in file. Please pass struct_name as one of {struct_names}") 

23 elif len(struct_names) == 0: 

24 raise RuntimeError(f"No structs in file") 

25 else: 

26 data = mat_file[struct_names[0]] 

27 

28 else: 

29 data = loadmat(filepath, simplify_cells=True)[struct_name] 

30 

31 return data 

32