mat73-reader 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ """mat73-reader: Read MATLAB v7.3 HDF5 .mat files in Python."""
2
+
3
+ from mat73_reader.reader import load, inspect
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["load", "inspect"]
mat73_reader/cli.py ADDED
@@ -0,0 +1,108 @@
1
+ """Command-line interface for mat73-reader."""
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from mat73_reader.reader import inspect, load
8
+ from mat73_reader.converter import to_csv, to_json
9
+
10
+
11
+ def main():
12
+ parser = argparse.ArgumentParser(
13
+ prog="mat73-reader",
14
+ description="Read and convert MATLAB v7.3 HDF5 .mat files.",
15
+ )
16
+ subparsers = parser.add_subparsers(dest="command", required=True)
17
+
18
+ # --- inspect ---
19
+ inspect_parser = subparsers.add_parser(
20
+ "inspect",
21
+ help="List variables in a .mat file with their types and shapes.",
22
+ )
23
+ inspect_parser.add_argument("file", type=Path, help="Path to .mat file")
24
+
25
+ # --- convert ---
26
+ convert_parser = subparsers.add_parser(
27
+ "convert",
28
+ help="Convert a .mat file to CSV or JSON.",
29
+ )
30
+ convert_parser.add_argument("file", type=Path, help="Path to .mat file")
31
+ convert_parser.add_argument(
32
+ "--format",
33
+ choices=["csv", "json"],
34
+ default="csv",
35
+ help="Output format (default: csv)",
36
+ )
37
+ convert_parser.add_argument(
38
+ "--output",
39
+ type=Path,
40
+ default=None,
41
+ help="Output path. For CSV: directory. For JSON: file path. "
42
+ "Defaults to current directory.",
43
+ )
44
+ convert_parser.add_argument(
45
+ "--variable",
46
+ type=str,
47
+ default=None,
48
+ help="Extract only this variable.",
49
+ )
50
+
51
+ args = parser.parse_args()
52
+
53
+ if args.command == "inspect":
54
+ _cmd_inspect(args)
55
+ elif args.command == "convert":
56
+ _cmd_convert(args)
57
+
58
+
59
+ def _cmd_inspect(args):
60
+ try:
61
+ variables = inspect(args.file)
62
+ except (FileNotFoundError, ValueError) as e:
63
+ print(f"Error: {e}", file=sys.stderr)
64
+ sys.exit(1)
65
+
66
+ if not variables:
67
+ print("No variables found.")
68
+ return
69
+
70
+ # Simple tabular output
71
+ print(f"{'Variable':<30} {'Type':<10} {'Shape/Children'}")
72
+ print("-" * 70)
73
+ for var in variables:
74
+ name = var["name"]
75
+ vtype = var["type"]
76
+ if vtype == "dataset":
77
+ detail = f"{var['shape']} {var['dtype']}"
78
+ else:
79
+ detail = ", ".join(var.get("children", []))
80
+ print(f"{name:<30} {vtype:<10} {detail}")
81
+
82
+
83
+ def _cmd_convert(args):
84
+ try:
85
+ if args.variable:
86
+ raw = load(args.file, variable=args.variable)
87
+ data = {args.variable: raw}
88
+ else:
89
+ data = load(args.file)
90
+ except (FileNotFoundError, ValueError, KeyError) as e:
91
+ print(f"Error: {e}", file=sys.stderr)
92
+ sys.exit(1)
93
+
94
+ if args.format == "csv":
95
+ output_dir = args.output or Path(".")
96
+ written = to_csv(data, output_dir)
97
+ for path in written:
98
+ print(f"Written: {path}")
99
+ if not written:
100
+ print("No variables could be converted to CSV.")
101
+ elif args.format == "json":
102
+ output_path = args.output or Path(f"{args.file.stem}.json")
103
+ written = to_json(data, output_path)
104
+ print(f"Written: {written}")
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
@@ -0,0 +1,97 @@
1
+ """Convert loaded MATLAB v7.3 data to common output formats."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Any, Union
6
+
7
+ import numpy as np
8
+
9
+
10
+ def to_csv(
11
+ data: dict,
12
+ output_dir: Union[str, Path],
13
+ prefix: str = "",
14
+ ) -> list[Path]:
15
+ """Write loaded .mat data to CSV files.
16
+
17
+ Each top-level variable that can be represented as a table
18
+ gets its own CSV file. Non-tabular data is skipped with a warning.
19
+
20
+ Args:
21
+ data: Dict returned by mat73_reader.load().
22
+ output_dir: Directory to write CSV files into.
23
+ prefix: Optional prefix for output filenames.
24
+
25
+ Returns:
26
+ List of paths to written CSV files.
27
+ """
28
+ import pandas as pd
29
+
30
+ output_dir = Path(output_dir)
31
+ output_dir.mkdir(parents=True, exist_ok=True)
32
+ written = []
33
+
34
+ for name, value in data.items():
35
+ filename = f"{prefix}{name}.csv" if prefix else f"{name}.csv"
36
+ out_path = output_dir / filename
37
+
38
+ if isinstance(value, pd.DataFrame):
39
+ value.to_csv(out_path, index=False)
40
+ written.append(out_path)
41
+ elif isinstance(value, np.ndarray) and value.ndim <= 2:
42
+ df = pd.DataFrame(value)
43
+ df.to_csv(out_path, index=False)
44
+ written.append(out_path)
45
+ elif isinstance(value, dict):
46
+ try:
47
+ df = pd.DataFrame(value)
48
+ df.to_csv(out_path, index=False)
49
+ written.append(out_path)
50
+ except (ValueError, TypeError):
51
+ print(f"Skipping '{name}': cannot convert to tabular CSV.")
52
+ else:
53
+ print(f"Skipping '{name}': unsupported type {type(value).__name__}.")
54
+
55
+ return written
56
+
57
+
58
+ def to_json(
59
+ data: dict,
60
+ output_path: Union[str, Path],
61
+ indent: int = 2,
62
+ ) -> Path:
63
+ """Write loaded .mat data to a JSON file.
64
+
65
+ Args:
66
+ data: Dict returned by mat73_reader.load().
67
+ output_path: Path for the output JSON file.
68
+ indent: JSON indentation level.
69
+
70
+ Returns:
71
+ Path to the written JSON file.
72
+ """
73
+ output_path = Path(output_path)
74
+ output_path.parent.mkdir(parents=True, exist_ok=True)
75
+
76
+ serializable = _make_serializable(data)
77
+ with open(output_path, "w") as f:
78
+ json.dump(serializable, f, indent=indent)
79
+
80
+ return output_path
81
+
82
+
83
+ def _make_serializable(obj: Any) -> Any:
84
+ """Recursively convert numpy types to JSON-serializable Python types."""
85
+ if isinstance(obj, dict):
86
+ return {k: _make_serializable(v) for k, v in obj.items()}
87
+ if isinstance(obj, list):
88
+ return [_make_serializable(item) for item in obj]
89
+ if isinstance(obj, np.ndarray):
90
+ return obj.tolist()
91
+ if isinstance(obj, (np.integer,)):
92
+ return int(obj)
93
+ if isinstance(obj, (np.floating,)):
94
+ return float(obj)
95
+ if isinstance(obj, np.bool_):
96
+ return bool(obj)
97
+ return obj
mat73_reader/reader.py ADDED
@@ -0,0 +1,402 @@
1
+ """Core reader for MATLAB v7.3 HDF5 .mat files."""
2
+
3
+ from pathlib import Path
4
+ from typing import Any, Optional, Union
5
+
6
+ import h5py
7
+ import numpy as np
8
+
9
+ # MATLAB MCOS (MATLAB Class Object System) class marker.
10
+ # Table objects in v7.3 files store a (1,6) uint32 header where
11
+ # the first element is this value.
12
+ _MCOS_CLASS_MARKER = 0xDD000000
13
+
14
+ # Number of MCOS ref slots per table instance.
15
+ # Each table occupies a fixed block of consecutive entries in the
16
+ # #subsystem#/MCOS reference array:
17
+ # +0: (ncols, 1) object refs -> column data arrays
18
+ # +1: (1,1) float64 = ndims
19
+ # +2: (1,1) float64 = nrows
20
+ # +3: (2,) uint64 = segment info
21
+ # +4: (1,1) float64 = nvars (ncols)
22
+ # +5: (ncols, 1) object refs -> column name strings (uint16)
23
+ # +6: Group = table properties (DimensionNames, VariableUnits, etc.)
24
+ _MCOS_BLOCK_SIZE = 7
25
+
26
+ # Offset of the first table block within the MCOS refs array.
27
+ _MCOS_BLOCK_BASE = 2
28
+
29
+
30
+ def load(
31
+ filepath: Union[str, Path],
32
+ variable: Optional[str] = None,
33
+ as_dataframe: bool = False,
34
+ ) -> Union[dict, Any]:
35
+ """Load a MATLAB v7.3 HDF5 .mat file.
36
+
37
+ Supports standard arrays, structs, cell arrays, char arrays,
38
+ and MATLAB table objects (which most Python tools cannot read).
39
+
40
+ Args:
41
+ filepath: Path to the .mat file.
42
+ variable: If provided, return only this top-level variable.
43
+ If None, return all variables as a dict.
44
+ as_dataframe: If True, attempt to convert array results to
45
+ pandas DataFrames. MATLAB tables are always returned as
46
+ DataFrames regardless of this flag.
47
+
48
+ Returns:
49
+ A dict mapping variable names to their values, or a single
50
+ value if `variable` is specified.
51
+
52
+ Raises:
53
+ FileNotFoundError: If the file does not exist.
54
+ ValueError: If the file is not a valid HDF5 .mat file.
55
+ KeyError: If the requested variable does not exist.
56
+ """
57
+ filepath = Path(filepath)
58
+ if not filepath.exists():
59
+ raise FileNotFoundError(f"File not found: {filepath}")
60
+
61
+ if not _is_mat73(filepath):
62
+ raise ValueError(
63
+ f"Not a MATLAB v7.3 HDF5 file: {filepath}. "
64
+ "For older .mat formats, use scipy.io.loadmat()."
65
+ )
66
+
67
+ with h5py.File(filepath, "r") as f:
68
+ # Pre-load the MCOS reference array if it exists.
69
+ # This is needed to resolve MATLAB table objects.
70
+ mcos_refs = _load_mcos_refs(f)
71
+
72
+ if variable is not None:
73
+ if variable not in f:
74
+ available = [
75
+ k for k in f.keys()
76
+ if k not in ("#refs#", "#subsystem#")
77
+ ]
78
+ raise KeyError(
79
+ f"Variable '{variable}' not found. "
80
+ f"Available: {available}"
81
+ )
82
+ result = _read_item(f[variable], f, mcos_refs)
83
+ if as_dataframe:
84
+ result = _try_to_dataframe(result, variable)
85
+ return result
86
+
87
+ data = {}
88
+ for key in f.keys():
89
+ if key in ("#refs#", "#subsystem#"):
90
+ continue
91
+ data[key] = _read_item(f[key], f, mcos_refs)
92
+
93
+ if as_dataframe:
94
+ data = {k: _try_to_dataframe(v, k) for k, v in data.items()}
95
+
96
+ return data
97
+
98
+
99
+ def inspect(filepath: Union[str, Path]) -> list[dict]:
100
+ """Inspect the contents of a MATLAB v7.3 HDF5 .mat file.
101
+
102
+ Returns a list of dicts describing each top-level variable:
103
+ name, type, shape, and dtype (for arrays).
104
+
105
+ Args:
106
+ filepath: Path to the .mat file.
107
+
108
+ Returns:
109
+ List of variable info dicts.
110
+ """
111
+ filepath = Path(filepath)
112
+ if not filepath.exists():
113
+ raise FileNotFoundError(f"File not found: {filepath}")
114
+
115
+ if not _is_mat73(filepath):
116
+ raise ValueError(
117
+ f"Not a MATLAB v7.3 HDF5 file: {filepath}. "
118
+ "For older .mat formats, use scipy.io.loadmat()."
119
+ )
120
+
121
+ variables = []
122
+ with h5py.File(filepath, "r") as f:
123
+ for key in f.keys():
124
+ if key in ("#refs#", "#subsystem#"):
125
+ continue
126
+ item = f[key]
127
+ info = {"name": key}
128
+ if isinstance(item, h5py.Dataset):
129
+ info["type"] = "dataset"
130
+ info["shape"] = item.shape
131
+ info["dtype"] = str(item.dtype)
132
+ elif isinstance(item, h5py.Group):
133
+ info["type"] = "group"
134
+ info["children"] = [k for k in item.keys()]
135
+ variables.append(info)
136
+
137
+ return variables
138
+
139
+
140
+ # ---------------------------------------------------------------------------
141
+ # MCOS table support
142
+ # ---------------------------------------------------------------------------
143
+
144
+ def _load_mcos_refs(f: h5py.File) -> Optional[np.ndarray]:
145
+ """Load the MCOS reference array if the file has one.
146
+
147
+ The #subsystem#/MCOS dataset is an object reference array that
148
+ MATLAB uses to store class instance data, including table columns
149
+ and metadata. We load it once and pass it through the read pipeline
150
+ so table objects can be resolved.
151
+ """
152
+ try:
153
+ mcos = f["#subsystem#"]["MCOS"]
154
+ return mcos[()]
155
+ except (KeyError, Exception):
156
+ return None
157
+
158
+
159
+ def _is_mcos_table_header(dataset: h5py.Dataset) -> bool:
160
+ """Check if a dataset is a MATLAB MCOS table header.
161
+
162
+ MATLAB table objects are stored as (1,6) uint32 arrays where
163
+ the first element is the MCOS class marker 0xDD000000.
164
+ """
165
+ if dataset.shape != (1, 6):
166
+ return False
167
+ if dataset.dtype != np.dtype("uint32"):
168
+ return False
169
+ first_val = dataset[0, 0]
170
+ return int(first_val) == _MCOS_CLASS_MARKER
171
+
172
+
173
+ def _read_mcos_table(
174
+ dataset: h5py.Dataset,
175
+ root: h5py.File,
176
+ mcos_refs: np.ndarray,
177
+ ) -> Any:
178
+ """Decode a MATLAB table object into a pandas DataFrame.
179
+
180
+ The (1,6) uint32 header encodes:
181
+ [0]: 0xDD000000 (MCOS class marker)
182
+ [1]: class definition index (same for all tables in a file)
183
+ [2]: reserved
184
+ [3]: reserved
185
+ [4]: instance index (1-based, determines which MCOS block)
186
+ [5]: reserved
187
+
188
+ The instance index maps to a block of 7 consecutive entries in
189
+ the MCOS reference array starting at offset:
190
+ mcos_ref_index = _MCOS_BLOCK_BASE + (instance - 1) * _MCOS_BLOCK_SIZE
191
+ """
192
+ import pandas as pd
193
+
194
+ header = dataset[()].ravel()
195
+ instance = int(header[4])
196
+ block_start = _MCOS_BLOCK_BASE + (instance - 1) * _MCOS_BLOCK_SIZE
197
+
198
+ refs_flat = mcos_refs.ravel()
199
+
200
+ # Safety check
201
+ if block_start + _MCOS_BLOCK_SIZE > len(refs_flat):
202
+ return None
203
+
204
+ # +0: column data references (ncols, 1)
205
+ data_ref_array = root[refs_flat[block_start]]
206
+ ncols = data_ref_array.shape[0]
207
+
208
+ # +5: column name references (ncols, 1)
209
+ name_ref_array = root[refs_flat[block_start + 5]]
210
+
211
+ # Read column names
212
+ col_names = []
213
+ for i in range(ncols):
214
+ ref = name_ref_array[i, 0]
215
+ name_ds = root[ref]
216
+ if name_ds.dtype == np.uint16:
217
+ col_names.append(_decode_chars(name_ds[()]))
218
+ else:
219
+ col_names.append(f"col_{i}")
220
+
221
+ # Read column data
222
+ columns = {}
223
+ for i, name in enumerate(col_names):
224
+ ref = data_ref_array[i, 0]
225
+ col_ds = root[ref]
226
+
227
+ if col_ds.dtype == np.float64:
228
+ columns[name] = col_ds[()].ravel()
229
+ elif col_ds.dtype == np.uint16:
230
+ columns[name] = _decode_chars(col_ds[()])
231
+ elif col_ds.dtype == h5py.ref_dtype:
232
+ # Column of object references (e.g., cell array column)
233
+ col_data = []
234
+ for j in range(col_ds.shape[0] if col_ds.ndim == 1 else col_ds.shape[1]):
235
+ r = col_ds[0, j] if col_ds.ndim == 2 else col_ds[j]
236
+ try:
237
+ inner = root[r]
238
+ if isinstance(inner, h5py.Dataset):
239
+ if inner.dtype == np.uint16:
240
+ col_data.append(_decode_chars(inner[()]))
241
+ elif inner.dtype == np.float64:
242
+ val = inner[()].ravel()
243
+ col_data.append(
244
+ val[0] if val.size == 1 else val
245
+ )
246
+ else:
247
+ col_data.append(inner[()])
248
+ else:
249
+ col_data.append(None)
250
+ except Exception:
251
+ col_data.append(None)
252
+ columns[name] = col_data
253
+ elif col_ds.dtype in (np.int64, np.int32, np.uint64, np.uint32):
254
+ columns[name] = col_ds[()].ravel()
255
+ else:
256
+ # Fallback: try to read raw
257
+ columns[name] = col_ds[()].ravel()
258
+
259
+ # Build DataFrame, handling ragged columns gracefully
260
+ try:
261
+ return pd.DataFrame(columns)
262
+ except ValueError:
263
+ # Columns may have different lengths (shouldn't happen for valid
264
+ # tables, but handle defensively)
265
+ max_len = max(
266
+ (len(v) if hasattr(v, '__len__') and not isinstance(v, str) else 1)
267
+ for v in columns.values()
268
+ )
269
+ padded = {}
270
+ for k, v in columns.items():
271
+ if isinstance(v, str):
272
+ padded[k] = [v] * max_len
273
+ elif hasattr(v, '__len__'):
274
+ arr = list(v)
275
+ arr.extend([None] * (max_len - len(arr)))
276
+ padded[k] = arr
277
+ else:
278
+ padded[k] = [v] * max_len
279
+ return pd.DataFrame(padded)
280
+
281
+
282
+ # ---------------------------------------------------------------------------
283
+ # Core reading functions
284
+ # ---------------------------------------------------------------------------
285
+
286
+ def _is_mat73(filepath: Path) -> bool:
287
+ """Check if a file is a valid HDF5-based MATLAB v7.3 file."""
288
+ try:
289
+ return h5py.is_hdf5(str(filepath))
290
+ except Exception:
291
+ return False
292
+
293
+
294
+ def _read_item(
295
+ item: Any,
296
+ root: h5py.File,
297
+ mcos_refs: Optional[np.ndarray] = None,
298
+ ) -> Any:
299
+ """Recursively read an HDF5 item into a Python object.
300
+
301
+ Handles datasets, groups (structs), object references,
302
+ cell arrays, char arrays, and MATLAB table objects.
303
+ """
304
+ if isinstance(item, h5py.Dataset):
305
+ return _read_dataset(item, root, mcos_refs)
306
+ elif isinstance(item, h5py.Group):
307
+ return _read_group(item, root, mcos_refs)
308
+ return item
309
+
310
+
311
+ def _read_dataset(
312
+ dataset: h5py.Dataset,
313
+ root: h5py.File,
314
+ mcos_refs: Optional[np.ndarray] = None,
315
+ ) -> Any:
316
+ """Read an HDF5 dataset, handling MATLAB-specific encodings."""
317
+ # Check for MATLAB table objects first
318
+ if mcos_refs is not None and _is_mcos_table_header(dataset):
319
+ return _read_mcos_table(dataset, root, mcos_refs)
320
+
321
+ data = dataset[()]
322
+
323
+ # MATLAB stores strings as uint16 arrays
324
+ if dataset.dtype == np.dtype("uint16"):
325
+ return _decode_chars(data)
326
+
327
+ # Object references (e.g., cell arrays)
328
+ if dataset.dtype == h5py.ref_dtype:
329
+ return _read_references(data, root, mcos_refs)
330
+
331
+ # Squeeze single-element arrays to scalars
332
+ if isinstance(data, np.ndarray):
333
+ if data.ndim == 0:
334
+ return data.item()
335
+ if data.shape == (1, 1):
336
+ return data[0, 0]
337
+ # MATLAB stores arrays in column-major (Fortran) order
338
+ # Transpose 2D arrays to match expected row-major layout
339
+ if data.ndim == 2:
340
+ return data.T
341
+
342
+ return data
343
+
344
+
345
+ def _read_group(
346
+ group: h5py.Group,
347
+ root: h5py.File,
348
+ mcos_refs: Optional[np.ndarray] = None,
349
+ ) -> dict:
350
+ """Read an HDF5 group as a dict (MATLAB struct)."""
351
+ result = {}
352
+ for key in group.keys():
353
+ result[key] = _read_item(group[key], root, mcos_refs)
354
+ return result
355
+
356
+
357
+ def _read_references(
358
+ data: np.ndarray,
359
+ root: h5py.File,
360
+ mcos_refs: Optional[np.ndarray] = None,
361
+ ) -> list:
362
+ """Resolve an array of HDF5 object references."""
363
+ refs = []
364
+ flat = data.flat
365
+ for ref in flat:
366
+ if isinstance(ref, h5py.Reference):
367
+ try:
368
+ dereferenced = root[ref]
369
+ refs.append(_read_item(dereferenced, root, mcos_refs))
370
+ except Exception:
371
+ refs.append(None)
372
+ else:
373
+ refs.append(ref)
374
+ return refs
375
+
376
+
377
+ def _decode_chars(data: np.ndarray) -> str:
378
+ """Decode MATLAB char arrays stored as uint16."""
379
+ if data.ndim == 0:
380
+ return chr(int(data))
381
+ flat = data.flatten()
382
+ return "".join(chr(c) for c in flat)
383
+
384
+
385
+ def _try_to_dataframe(value: Any, name: str) -> Any:
386
+ """Attempt to convert a value to a pandas DataFrame."""
387
+ import pandas as pd
388
+
389
+ # MATLAB tables are already DataFrames
390
+ if isinstance(value, pd.DataFrame):
391
+ return value
392
+
393
+ if isinstance(value, np.ndarray) and value.ndim == 2:
394
+ return pd.DataFrame(value)
395
+ if isinstance(value, dict):
396
+ # Try to build a DataFrame from a struct where each field
397
+ # is an array of the same length (common MATLAB table pattern)
398
+ try:
399
+ return pd.DataFrame(value)
400
+ except (ValueError, TypeError):
401
+ return value
402
+ return value
@@ -0,0 +1,213 @@
1
+ Metadata-Version: 2.4
2
+ Name: mat73-reader
3
+ Version: 0.1.0
4
+ Summary: Read MATLAB v7.3 HDF5 .mat files that scipy.io.loadmat cannot handle.
5
+ Author-email: William Garrow <williamgarrow@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Keywords: hdf5,mat73,matlab,scientific-data,scipy
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering
14
+ Requires-Python: >=3.9
15
+ Requires-Dist: h5py>=3.0
16
+ Requires-Dist: numpy>=1.20
17
+ Requires-Dist: pandas>=1.3
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest-cov; extra == 'dev'
20
+ Requires-Dist: pytest>=7.0; extra == 'dev'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # mat73-reader
24
+
25
+ Read MATLAB v7.3 HDF5 `.mat` files in Python. **including MATLAB table objects** that other tools cannot decode.
26
+
27
+ ## The MATLAB Table Problem
28
+
29
+ MATLAB v7.3 stores table objects using an undocumented internal system called MCOS (MATLAB Class Object System). Every existing Python tool (`scipy.io.loadmat()`, `mat73`, `hdf5storage`) fails on them:
30
+
31
+ ```python
32
+ # scipy can't even open v7.3 files
33
+ >>> scipy.io.loadmat("experiment.mat")
34
+ NotImplementedError: Please use HDF reader for matlab v7.3 files
35
+
36
+ # mat73 opens the file but returns None for every table
37
+ >>> import mat73
38
+ >>> data = mat73.loadmat("experiment.mat")
39
+ ERROR: MATLAB type not supported: table, (uint32) # x 800
40
+ >>> data["task"]["gaze"][0]
41
+ None
42
+ ```
43
+
44
+ Tables are used extensively in neuroscience, signal processing, cognitive science, biomechanics, and clinical research datasets. If your `.mat` file contains tables, **mat73-reader is currently the only Python tool that can read them.**
45
+
46
+ ```python
47
+ >>> from mat73_reader import load
48
+ >>> data = load("experiment.mat")
49
+ >>> data["task"]["gaze"][0]
50
+ gaze_timestamp world_index confidence norm_pos_x norm_pos_y ...
51
+ 0 5410.551714 0.0 0.999499 0.446264 0.846886 ...
52
+ 1 5410.555834 0.0 0.999653 0.446534 0.847007 ...
53
+ 2 5410.559773 0.0 0.999648 0.446660 0.846410 ...
54
+ ...
55
+ [8205 rows x 21 columns]
56
+ ```
57
+
58
+ ## How It Works
59
+
60
+ When other tools encounter a MATLAB table, they see a `(1,6) uint32` header and stop. mat73-reader decodes the MCOS block structure to follow the reference chain to the actual data:
61
+
62
+ ```mermaid
63
+ graph TD
64
+ subgraph "What other tools see"
65
+ A["Table Header<br/>(1,6) uint32<br/>0xDD000000 ..."] -->|"???"| B["None"]
66
+ end
67
+
68
+ subgraph "What mat73-reader decodes"
69
+ H["Table Header<br/>(1,6) uint32"] -->|"instance index"| M["MCOS Reference Array<br/>#subsystem#/MCOS"]
70
+ M -->|"block offset + 0"| D["Column Data Refs<br/>(ncols, 1) object"]
71
+ M -->|"block offset + 5"| N["Column Name Refs<br/>(ncols, 1) object"]
72
+ D -->|"dereference"| D1["timestamp<br/>float64 (1, N)"]
73
+ D -->|"dereference"| D2["confidence<br/>float64 (1, N)"]
74
+ D -->|"dereference"| D3["...<br/>float64 (1, N)"]
75
+ N -->|"dereference"| N1["'gaze_timestamp'<br/>uint16 chars"]
76
+ N -->|"dereference"| N2["'confidence'<br/>uint16 chars"]
77
+ N -->|"dereference"| N3["'...'<br/>uint16 chars"]
78
+ D1 & D2 & D3 & N1 & N2 & N3 -->|"assemble"| DF["pandas DataFrame"]
79
+ end
80
+
81
+ style B fill:#ff6b6b,color:#fff
82
+ style DF fill:#51cf66,color:#fff
83
+ ```
84
+
85
+ Each table instance occupies a fixed block of 7 consecutive entries in the MCOS reference array:
86
+
87
+ ```
88
+ Block layout (7 slots per table):
89
+ +0 (ncols, 1) object refs --> column data arrays (float64, int, etc.)
90
+ +1 (1, 1) float64 --> ndims
91
+ +2 (1, 1) float64 --> nrows
92
+ +3 (2,) uint64 --> segment info
93
+ +4 (1, 1) float64 --> nvars (number of columns)
94
+ +5 (ncols, 1) object refs --> column name strings (uint16-encoded)
95
+ +6 Group --> table properties (units, descriptions, etc.)
96
+ ```
97
+
98
+ The instance index from the table header maps to a block offset:
99
+
100
+ ```
101
+ block_start = 2 + (instance - 1) * 7
102
+ ```
103
+
104
+ This structure is not documented by MathWorks. It was reverse-engineered by analyzing real-world scientific datasets.
105
+
106
+ ## Real-World Validation
107
+
108
+ mat73-reader has been validated against the [COLET dataset](https://zenodo.org/records/7766785) (Cognitive workLoad Estimation via Eye-Tracking), a 3.8 GB MATLAB v7.3 file containing:
109
+
110
+ - 47 subjects, 4 tasks per subject
111
+ - 4 data fields per task (gaze, pupil, blinks, annotation)
112
+ - **752 MATLAB table objects** total
113
+ - Over 14,000 individual data arrays
114
+
115
+ Every table was successfully decoded into a pandas DataFrame with correct column names and data types. Other Python tools return `None` for all 752 tables.
116
+
117
+ ## Installation
118
+
119
+ ```bash
120
+ pip install mat73-reader
121
+ ```
122
+
123
+ Or install from source:
124
+
125
+ ```bash
126
+ git clone https://github.com/WilliamGarrow/mat73-reader.git
127
+ cd mat73-reader
128
+ pip install -e ".[dev]"
129
+ ```
130
+
131
+ ## Usage
132
+
133
+ ### Python API
134
+
135
+ ```python
136
+ from mat73_reader import load, inspect
137
+
138
+ # Inspect file contents without loading data
139
+ variables = inspect("experiment.mat")
140
+ for var in variables:
141
+ print(var)
142
+
143
+ # Load everything
144
+ data = load("experiment.mat")
145
+
146
+ # Load a specific top-level variable
147
+ results = load("experiment.mat", variable="results")
148
+
149
+ # Force all compatible arrays to pandas DataFrames
150
+ data = load("experiment.mat", as_dataframe=True)
151
+ ```
152
+
153
+ MATLAB tables are always returned as DataFrames automatically, no flags needed.
154
+
155
+ ### Command Line
156
+
157
+ ```bash
158
+ # List variables, types, and shapes
159
+ mat73-reader inspect experiment.mat
160
+
161
+ # Convert to CSV (one file per variable)
162
+ mat73-reader convert experiment.mat --format csv --output ./csv_output/
163
+
164
+ # Convert to JSON
165
+ mat73-reader convert experiment.mat --format json --output experiment.json
166
+
167
+ # Convert a single variable
168
+ mat73-reader convert experiment.mat --variable gaze_data --format csv
169
+ ```
170
+
171
+ ## What It Handles
172
+
173
+ | MATLAB Type | Python Type | Notes |
174
+ |------------|-------------|-------|
175
+ | **Table objects** | **`pandas.DataFrame`** | **Column names and data types preserved** |
176
+ | Numeric arrays | `numpy.ndarray` | Transposed to row-major order |
177
+ | Structs | `dict` | Nested to arbitrary depth |
178
+ | Cell arrays | `list` | HDF5 object references resolved |
179
+ | Char arrays | `str` | Decoded from uint16 |
180
+ | Scalars | Python `int`/`float` | Single-element arrays squeezed |
181
+
182
+ ## When to Use This vs. Other Tools
183
+
184
+ | Scenario | Tool |
185
+ |----------|------|
186
+ | `.mat` v5 or earlier (no tables) | `scipy.io.loadmat()` |
187
+ | `.mat` v7.3 with arrays and structs only | `mat73` or **mat73-reader** |
188
+ | `.mat` v7.3 with **table objects** | **mat73-reader** (only option in Python) |
189
+ | Not sure what format you have | Try `mat73-reader` first; it will tell you if it's not v7.3 |
190
+
191
+ ## Development
192
+
193
+ ```bash
194
+ git clone https://github.com/WilliamGarrow/mat73-reader.git
195
+ cd mat73-reader
196
+ python -m venv .venv
197
+ source .venv/bin/activate
198
+ pip install -e ".[dev]"
199
+ pytest
200
+ ```
201
+
202
+ ### Test Suite
203
+
204
+ 38 tests covering:
205
+ - Standard v7.3 reading (arrays, structs, cell arrays, char arrays, scalars)
206
+ - MCOS table header detection (positive and negative cases)
207
+ - Single and multi-table decoding with synthetic fixtures
208
+ - Column name extraction and data value verification
209
+ - Edge cases (non-table uint32 arrays, missing variables, invalid files)
210
+
211
+ ## License
212
+
213
+ Apache 2.0. See [LICENSE](LICENSE) for details.
@@ -0,0 +1,9 @@
1
+ mat73_reader/__init__.py,sha256=KHaNaOkshxbEYycuLeOPx-ig3ggkKu6UYNQzQtsXQ-4,164
2
+ mat73_reader/cli.py,sha256=BXA3yBqD5_TWa5YVQyuoQp8HA9R-V76Yn6KwDsaz8M4,3052
3
+ mat73_reader/converter.py,sha256=dxKEped_JZ9ELI9BFGE1CfOV5CS4Q7a82PoOtge0LII,2864
4
+ mat73_reader/reader.py,sha256=0-MuCxqsx-bULtAoInlG7BszS92djpPswzx-D8PPOCg,13082
5
+ mat73_reader-0.1.0.dist-info/METADATA,sha256=81D9HeZQS7zkhgBYvophLKCBzQ-S8WCxUu69oYHUUOE,7314
6
+ mat73_reader-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
7
+ mat73_reader-0.1.0.dist-info/entry_points.txt,sha256=_g3IHPl5X6dgH3hib5MORe7q0o9Cuh2Jg3P5JeVWleQ,55
8
+ mat73_reader-0.1.0.dist-info/licenses/LICENSE,sha256=OMUDZnvIFu9yLKN2HgPTsMmNUvEoVg7unVEm_YWtUpE,10765
9
+ mat73_reader-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ mat73-reader = mat73_reader.cli:main
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 William Garrow
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.