Datasets:
License:
File size: 15,474 Bytes
2034f5f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 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 | #!/usr/bin/env python3
"""
PHM-Vibench Metadata 快速验证和修复脚本
用于检查和修复 metadata_25_10_30.xlsx 中的关键问题
"""
import pandas as pd
import numpy as np
import h5py
import os
from datetime import datetime
import json
import sys
class MetadataChecker:
def __init__(self):
self.base_path = '/home/user/data/PHMbenchdata/PHM-Vibench'
self.metadata_path = os.path.join(self.base_path, 'metadata_25_10_30.xlsx')
self.h5_path = os.path.join(self.base_path, 'metadata_6_1.h5')
self.backup_path = os.path.join(self.base_path, 'backups')
self.log_path = os.path.join(self.base_path, 'log')
# 确保目录存在
os.makedirs(self.backup_path, exist_ok=True)
os.makedirs(self.log_path, exist_ok=True)
def load_metadata(self):
"""加载metadata文件"""
print(f"📂 加载 metadata 文件: {self.metadata_path}")
self.df = pd.read_excel(self.metadata_path)
print(f"✅ 成功加载 {len(self.df)} 条记录")
def check_h5_data(self):
"""检查H5文件中的实际数据维度"""
print("\n🔍 检查 H5 文件数据维度...")
if not os.path.exists(self.h5_path):
print(f"❌ H5文件不存在: {self.h5_path}")
return
with h5py.File(self.h5_path, 'r') as f:
# Dataset_id 18 对应的Id范围: 47288-47566
print("\n=== Dataset_id 18 (Id: 47288-47566) ===")
shapes_18 = []
for i in range(47288, min(47298, 47567)): # 检查前10个
key = str(i)
if key in f:
data = f[key][()]
if isinstance(data, np.ndarray):
shapes_18.append(data.shape)
print(f" Id {i}: shape={data.shape}")
# Dataset_id 20 对应的Id范围: 47567-50126
print("\n=== Dataset_id 20 (Id: 47567-47577) ===")
shapes_20 = []
for i in range(47567, min(47577, 50127)): # 检查前10个
key = str(i)
if key in f:
data = f[key][()]
if isinstance(data, np.ndarray):
shapes_20.append(data.shape)
print(f" Id {i}: shape={data.shape}")
# 更多抽样检查
print("\n=== 抽样统计 ===")
for i in range(47288, 47567, 20): # 每20个抽样
key = str(i)
if key in f:
data = f[key][()]
if isinstance(data, np.ndarray):
shapes_18.append(data.shape)
for i in range(47567, 50127, 100): # 每100个抽样
key = str(i)
if key in f:
data = f[key][()]
if isinstance(data, np.ndarray):
shapes_20.append(data.shape)
if shapes_18:
unique_shapes_18 = set(shapes_18)
print(f"\nDataset_id 18 数据维度分布:")
for shape in unique_shapes_18:
count = shapes_18.count(shape)
print(f" {shape}: {count} 次")
if shapes_20:
unique_shapes_20 = set(shapes_20)
print(f"\nDataset_id 20 数据维度分布:")
for shape in unique_shapes_20:
count = shapes_20.count(shape)
print(f" {shape}: {count} 次")
# 保存检查结果
self.h5_shapes_18 = shapes_18 if shapes_18 else []
self.h5_shapes_20 = shapes_20 if shapes_20 else []
def analyze_metadata_issues(self):
"""分析metadata中的问题"""
print("\n📊 分析 metadata 问题...")
# Dataset_id 18
df_18 = self.df[self.df['Dataset_id'] == 18]
print(f"\nDataset_id 18:")
print(f" 记录数: {len(df_18)}")
if len(df_18) > 0:
print(f" Channel: {df_18['Channel'].unique()}")
print(f" Sample_lenth: {df_18['Sample_lenth'].unique()}")
print(f" Name: {df_18['Name'].unique()}")
self.meta_channel_18 = df_18['Channel'].iloc[0]
self.meta_length_18 = df_18['Sample_lenth'].iloc[0]
# Dataset_id 20
df_20 = self.df[self.df['Dataset_id'] == 20]
print(f"\nDataset_id 20:")
print(f" 记录数: {len(df_20)}")
if len(df_20) > 0:
print(f" Channel: {df_20['Channel'].unique()}")
print(f" Sample_lenth: {df_20['Sample_lenth'].unique()}")
print(f" Name: {df_20['Name'].unique()}")
self.meta_channel_20 = df_20['Channel'].iloc[0]
self.meta_length_20 = df_20['Sample_lenth'].iloc[0]
def identify_issues(self):
"""识别需要修复的问题"""
print("\n⚠️ 识别问题...")
self.issues = []
# 检查Dataset_id 18
if hasattr(self, 'h5_shapes_18') and self.h5_shapes_18:
# 统计各种形状的出现次数
shape_counts_18 = {}
for shape in self.h5_shapes_18:
shape_counts_18[shape] = shape_counts_18.get(shape, 0) + 1
# 找出最常见的形状
most_common_shape = max(shape_counts_18.items(), key=lambda x: x[1])
actual_length = int(most_common_shape[0][0])
actual_channels = int(most_common_shape[0][1])
print(f"\nDataset_id 18 维度统计:")
for shape, count in sorted(shape_counts_18.items(), key=lambda x: x[1], reverse=True)[:5]:
print(f" {shape}: {count}次")
if self.meta_length_18 != actual_length:
self.issues.append({
'dataset_id': 18,
'type': 'sample_length_mismatch',
'metadata_value': self.meta_length_18,
'h5_value': actual_length,
'description': f"Sample_lenth不匹配: metadata={self.meta_length_18}, H5实际={actual_length}"
})
if self.meta_channel_18 != actual_channels:
self.issues.append({
'dataset_id': 18,
'type': 'channel_mismatch',
'metadata_value': self.meta_channel_18,
'h5_value': actual_channels,
'description': f"Channel不匹配: metadata={self.meta_channel_18}, H5实际={actual_channels}"
})
# 检查Dataset_id 20
if hasattr(self, 'h5_shapes_20') and self.h5_shapes_20:
# 统计各种形状的出现次数
shape_counts_20 = {}
for shape in self.h5_shapes_20:
shape_counts_20[shape] = shape_counts_20.get(shape, 0) + 1
# 找出最常见的形状
most_common_shape = max(shape_counts_20.items(), key=lambda x: x[1])
actual_length = int(most_common_shape[0][0])
actual_channels = int(most_common_shape[0][1])
print(f"\nDataset_id 20 维度统计:")
for shape, count in sorted(shape_counts_20.items(), key=lambda x: x[1], reverse=True)[:5]:
print(f" {shape}: {count}次")
if self.meta_length_20 != actual_length:
self.issues.append({
'dataset_id': 20,
'type': 'sample_length_mismatch',
'metadata_value': self.meta_length_20,
'h5_value': actual_length,
'description': f"Sample_lenth不匹配: metadata={self.meta_length_20}, H5实际={actual_length}"
})
if self.meta_channel_20 != actual_channels:
self.issues.append({
'dataset_id': 20,
'type': 'channel_mismatch',
'metadata_value': self.meta_channel_20,
'h5_value': actual_channels,
'description': f"Channel不匹配: metadata={self.meta_channel_20}, H5实际={actual_channels}"
})
# 输出问题汇总
if self.issues:
print(f"\n发现 {len(self.issues)} 个问题:")
for i, issue in enumerate(self.issues, 1):
print(f"\n问题 {i}: Dataset_id {issue['dataset_id']}")
print(f" 类型: {issue['type']}")
print(f" 描述: {issue['description']}")
else:
print("\n✅ 未发现明显问题")
def backup_metadata(self):
"""备份原始metadata文件"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_file = os.path.join(self.backup_path, f"metadata_25_10_30_backup_{timestamp}.xlsx")
print(f"\n💾 备份原始文件到: {backup_file}")
self.df.to_excel(backup_file, index=False)
print("✅ 备份完成")
return backup_file
def fix_metadata(self):
"""修复metadata中的问题"""
if not self.issues:
print("\n✅ 没有需要修复的问题")
return
print("\n🔧 开始修复 metadata...")
# 创建修复后的DataFrame副本
df_fixed = self.df.copy()
fix_log = []
for issue in self.issues:
dataset_id = issue['dataset_id']
if issue['type'] == 'sample_length_mismatch':
mask = df_fixed['Dataset_id'] == dataset_id
old_value = df_fixed.loc[mask, 'Sample_lenth'].iloc[0]
new_value = issue['h5_value']
df_fixed.loc[mask, 'Sample_lenth'] = new_value
fix_log.append({
'dataset_id': dataset_id,
'field': 'Sample_lenth',
'old_value': old_value,
'new_value': new_value,
'records_affected': mask.sum()
})
print(f" ✓ Dataset_id {dataset_id}: Sample_lenth {old_value} → {new_value}")
elif issue['type'] == 'channel_mismatch':
mask = df_fixed['Dataset_id'] == dataset_id
old_value = df_fixed.loc[mask, 'Channel'].iloc[0]
new_value = issue['h5_value']
df_fixed.loc[mask, 'Channel'] = new_value
fix_log.append({
'dataset_id': dataset_id,
'field': 'Channel',
'old_value': old_value,
'new_value': new_value,
'records_affected': mask.sum()
})
print(f" ✓ Dataset_id {dataset_id}: Channel {old_value} → {new_value}")
# 保存修复后的文件
fixed_file = os.path.join(self.base_path, 'metadata_25_10_30_fixed.xlsx')
df_fixed.to_excel(fixed_file, index=False)
print(f"\n✅ 修复后的文件保存到: {fixed_file}")
# 保存修复日志
log_file = os.path.join(self.log_path, 'fix_log.json')
# 转换numpy类型为python原生类型
issues_serializable = []
for issue in self.issues:
issue_copy = issue.copy()
if 'metadata_value' in issue_copy:
issue_copy['metadata_value'] = int(issue_copy['metadata_value']) if hasattr(issue_copy['metadata_value'], 'dtype') else issue_copy['metadata_value']
if 'h5_value' in issue_copy:
issue_copy['h5_value'] = int(issue_copy['h5_value']) if hasattr(issue_copy['h5_value'], 'dtype') else issue_copy['h5_value']
issues_serializable.append(issue_copy)
fixes_serializable = []
for fix in fix_log:
fix_copy = fix.copy()
for key in ['old_value', 'new_value']:
if key in fix_copy and hasattr(fix_copy[key], 'dtype'):
fix_copy[key] = int(fix_copy[key])
if 'records_affected' in fix_copy and hasattr(fix_copy['records_affected'], 'dtype'):
fix_copy['records_affected'] = int(fix_copy['records_affected'])
fixes_serializable.append(fix_copy)
with open(log_file, 'w', encoding='utf-8') as f:
json.dump({
'timestamp': datetime.now().isoformat(),
'issues_found': issues_serializable,
'fixes_applied': fixes_serializable
}, f, indent=2, ensure_ascii=False)
print(f"📝 修复日志保存到: {log_file}")
self.df_fixed = df_fixed
self.fix_log = fix_log
def generate_report(self):
"""生成验证报告"""
report = {
'timestamp': datetime.now().isoformat(),
'metadata_file': self.metadata_path,
'h5_file': self.h5_path,
'total_records': len(self.df),
'issues_found': len(self.issues) if hasattr(self, 'issues') else 0,
'dataset_analysis': {
'dataset_18': {
'id_range': '47288-47566',
'records': len(self.df[self.df['Dataset_id'] == 18]),
'metadata_channel': self.meta_channel_18 if hasattr(self, 'meta_channel_18') else None,
'metadata_length': self.meta_length_18 if hasattr(self, 'meta_length_18') else None
},
'dataset_20': {
'id_range': '47567-50126',
'records': len(self.df[self.df['Dataset_id'] == 20]),
'metadata_channel': self.meta_channel_20 if hasattr(self, 'meta_channel_20') else None,
'metadata_length': self.meta_length_20 if hasattr(self, 'meta_length_20') else None
}
}
}
report_file = os.path.join(self.log_path, 'validation_report.json')
with open(report_file, 'w', encoding='utf-8') as f:
json.dump(report, f, indent=2, ensure_ascii=False)
print(f"\n📊 验证报告保存到: {report_file}")
def run(self, auto_fix=False):
"""运行完整的验证和修复流程"""
print("=" * 60)
print("🚀 PHM-Vibench Metadata 验证和修复工具")
print("=" * 60)
# 1. 加载数据
self.load_metadata()
# 2. 检查H5数据
self.check_h5_data()
# 3. 分析metadata
self.analyze_metadata_issues()
# 4. 识别问题
self.identify_issues()
# 5. 备份
backup_file = self.backup_metadata()
# 6. 修复(如果需要)
if auto_fix and self.issues:
self.fix_metadata()
# 7. 生成报告
self.generate_report()
print("\n" + "=" * 60)
print("✅ 验证完成!")
print("=" * 60)
if hasattr(self, 'issues') and self.issues:
print(f"\n发现 {len(self.issues)} 个问题需要修复")
print("使用 --fix 参数执行自动修复")
else:
print("\n✅ 未发现问题")
def main():
import argparse
parser = argparse.ArgumentParser(description='PHM-Vibench Metadata 验证和修复工具')
parser.add_argument('--fix', action='store_true', help='自动修复发现的问题')
parser.add_argument('--check-only', action='store_true', help='仅检查不修复')
args = parser.parse_args()
checker = MetadataChecker()
if args.check_only:
checker.run(auto_fix=False)
else:
checker.run(auto_fix=args.fix)
if __name__ == "__main__":
main() |