Download AMVL/tool/inspect_mat.py from JX-Lab/QQCM: direct link, hf CLI and curl.
- Browser
- Download file 8.21 kB
-
https://huggingface.co/datasets/JX-Lab/QQCM/resolve/main/AMVL/tool/inspect_mat.py
- Command line
-
hf download hf://datasets/JX-Lab/QQCM/AMVL/tool/inspect_mat.py
-
curl -L -o inspect_mat.py https://huggingface.co/datasets/JX-Lab/QQCM/resolve/main/AMVL/tool/inspect_mat.py
8.21 kB
| """ | |
| MAT文件检查工具 | |
| 用于可视化打印.mat文件的内容,包括子表、维度等信息 | |
| """ | |
| import argparse | |
| import sys | |
| from pathlib import Path | |
| import scipy.io as sio | |
| import numpy as np | |
| def format_size(num_bytes): | |
| """格式化字节大小""" | |
| for unit in ['B', 'KB', 'MB', 'GB']: | |
| if num_bytes < 1024.0: | |
| return f"{num_bytes:.2f} {unit}" | |
| num_bytes /= 1024.0 | |
| return f"{num_bytes:.2f} TB" | |
| def get_array_info(arr): | |
| """获取数组的详细信息""" | |
| info = { | |
| 'type': type(arr).__name__, | |
| 'dtype': None, | |
| 'shape': None, | |
| 'size': None, | |
| 'memory': None, | |
| } | |
| if isinstance(arr, np.ndarray): | |
| info['dtype'] = str(arr.dtype) | |
| info['shape'] = arr.shape | |
| info['size'] = arr.size | |
| info['memory'] = format_size(arr.nbytes) | |
| elif hasattr(arr, '__len__'): | |
| info['length'] = len(arr) | |
| return info | |
| def print_separator(char='=', length=80): | |
| """打印分隔线""" | |
| print(char * length) | |
| def print_table(data_keys, mat_data): | |
| """以表格形式打印变量汇总信息""" | |
| # 收集所有变量信息 | |
| rows = [] | |
| for key in data_keys: | |
| value = mat_data[key] | |
| info = get_array_info(value) | |
| shape_str = str(info['shape']) if info['shape'] else 'N/A' | |
| dtype_str = info['dtype'] if info['dtype'] else info['type'] | |
| memory_str = info['memory'] if info['memory'] else 'N/A' | |
| rows.append({ | |
| 'name': key, | |
| 'shape': shape_str, | |
| 'dtype': dtype_str, | |
| 'memory': memory_str | |
| }) | |
| # 计算列宽 | |
| col_widths = { | |
| 'idx': max(3, len(str(len(rows)))), | |
| 'name': max(8, max(len(row['name']) for row in rows)), | |
| 'shape': max(6, max(len(row['shape']) for row in rows)), | |
| 'dtype': max(10, max(len(row['dtype']) for row in rows)), | |
| 'memory': max(6, max(len(row['memory']) for row in rows)) | |
| } | |
| # 打印表头 | |
| print("\n") | |
| print_separator('=', 80) | |
| print("变量汇总表") | |
| print_separator('=', 80) | |
| header = f"{'序号':^{col_widths['idx']}} | {'变量名':<{col_widths['name']}} | {'形状':<{col_widths['shape']}} | {'数据类型':<{col_widths['dtype']}} | {'内存占用':>{col_widths['memory']}}" | |
| print(header) | |
| print_separator('-', len(header)) | |
| # 打印数据行 | |
| for idx, row in enumerate(rows, 1): | |
| line = f"{idx:^{col_widths['idx']}} | {row['name']:<{col_widths['name']}} | {row['shape']:<{col_widths['shape']}} | {row['dtype']:<{col_widths['dtype']}} | {row['memory']:>{col_widths['memory']}}" | |
| print(line) | |
| print_separator('=', len(header)) | |
| print(f"总计: {len(rows)} 个变量\n") | |
| def inspect_mat_file(filepath, show_table=True): | |
| """检查并打印.mat文件的信息 | |
| Args: | |
| filepath: 文件路径 | |
| show_table: 是否显示汇总表格 | |
| Returns: | |
| tuple: (成功标志, 文件路径, 数据键列表, mat数据字典) | |
| """ | |
| filepath = Path(filepath) | |
| if not filepath.exists(): | |
| print(f"错误: 文件不存在 - {filepath}") | |
| return False, None, None, None | |
| if not filepath.suffix.lower() == '.mat': | |
| print(f"警告: 文件后缀不是.mat - {filepath}") | |
| try: | |
| # 读取.mat文件 | |
| print_separator() | |
| print(f"文件路径: {filepath.absolute()}") | |
| print(f"文件大小: {format_size(filepath.stat().st_size)}") | |
| print_separator() | |
| mat_data = sio.loadmat(str(filepath)) | |
| # 过滤掉MATLAB的元数据键 | |
| metadata_keys = ['__header__', '__version__', '__globals__'] | |
| data_keys = [k for k in mat_data.keys() if k not in metadata_keys] | |
| print(f"\n包含的变量数量: {len(data_keys)}\n") | |
| if not data_keys: | |
| print("文件中没有数据变量") | |
| return True, filepath, [], mat_data | |
| # 打印每个变量的详细信息 | |
| for idx, key in enumerate(data_keys, 1): | |
| print_separator('-', 80) | |
| print(f"[{idx}] 变量名: {key}") | |
| print_separator('-', 80) | |
| value = mat_data[key] | |
| info = get_array_info(value) | |
| print(f" 类型: {info['type']}") | |
| if info['dtype']: | |
| print(f" 数据类型: {info['dtype']}") | |
| if info['shape']: | |
| print(f" 形状: {info['shape']}") | |
| print(f" 维度: {len(info['shape'])}D") | |
| print(f" 元素总数: {info['size']:,}") | |
| if info['memory']: | |
| print(f" 内存占用: {info['memory']}") | |
| if 'length' in info: | |
| print(f" 长度: {info['length']}") | |
| # 如果是numpy数组,显示一些统计信息 | |
| if isinstance(value, np.ndarray): | |
| if np.issubdtype(value.dtype, np.number): | |
| print(f"\n 统计信息:") | |
| print(f" 最小值: {np.min(value)}") | |
| print(f" 最大值: {np.max(value)}") | |
| print(f" 平均值: {np.mean(value):.6f}") | |
| print(f" 标准差: {np.std(value):.6f}") | |
| # 显示数据预览 | |
| print(f"\n 数据预览:") | |
| with np.printoptions(precision=4, suppress=True, threshold=10): | |
| if value.size <= 100: | |
| print(f" {value}") | |
| else: | |
| print(f" {value.flat[:10]}...") | |
| print() | |
| # 打印汇总表格(仅当 show_table=True 时) | |
| if show_table: | |
| print_table(data_keys, mat_data) | |
| print_separator() | |
| print("检查完成") | |
| print_separator() | |
| return True, filepath, data_keys, mat_data | |
| except Exception as e: | |
| print(f"错误: 读取文件时出错 - {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return False, None, None, None | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description='可视化检查.mat文件的内容,显示包含的变量、维度等信息', | |
| formatter_class=argparse.RawDescriptionHelpFormatter, | |
| epilog=''' | |
| 示例用法: | |
| %(prog)s data/Fdataset/Fdataset.mat | |
| %(prog)s data/new_drug_prediction/Fdataset_new_drug.mat | |
| %(prog)s file1.mat file2.mat file3.mat | |
| ''' | |
| ) | |
| parser.add_argument( | |
| 'files', | |
| nargs='+', | |
| help='.mat文件的路径(可以指定多个文件)' | |
| ) | |
| parser.add_argument( | |
| '-v', '--version', | |
| action='version', | |
| version='%(prog)s 1.0' | |
| ) | |
| args = parser.parse_args() | |
| # 处理多个文件 | |
| success_count = 0 | |
| file_data_list = [] # 存储所有文件的数据,用于最后集中显示表格 | |
| multiple_files = len(args.files) > 1 | |
| for idx, filepath in enumerate(args.files, 1): | |
| if multiple_files: | |
| print(f"\n{'='*80}") | |
| print(f"处理文件 {idx}/{len(args.files)}") | |
| print(f"{'='*80}\n") | |
| # 多文件模式下不显示单独的表格 | |
| success, fpath, data_keys, mat_data = inspect_mat_file( | |
| filepath, | |
| show_table=not multiple_files | |
| ) | |
| if success: | |
| success_count += 1 | |
| if multiple_files and data_keys: | |
| file_data_list.append({ | |
| 'filepath': fpath, | |
| 'data_keys': data_keys, | |
| 'mat_data': mat_data | |
| }) | |
| if multiple_files: | |
| print("\n") | |
| # 多文件模式:集中显示所有文件的表格 | |
| if multiple_files and file_data_list: | |
| print(f"\n{'='*80}") | |
| print("所有文件的变量汇总") | |
| print(f"{'='*80}\n") | |
| for file_info in file_data_list: | |
| print(f"\n文件: {file_info['filepath'].name}") | |
| print_table(file_info['data_keys'], file_info['mat_data']) | |
| # 输出总结 | |
| if multiple_files: | |
| print(f"{'='*80}") | |
| print(f"总计: 成功 {success_count}/{len(args.files)} 个文件") | |
| print(f"{'='*80}") | |
| return 0 if success_count == len(args.files) else 1 | |
| if __name__ == '__main__': | |
| sys.exit(main()) | |