Files
rct/1.py
T
2026-02-03 15:37:03 +08:00

452 lines
16 KiB
Python

import os
import zipfile
import shutil
import pandas as pd
import numpy as np
from scipy.signal import butter, sosfiltfilt
from scipy.stats import kurtosis
from scipy.interpolate import CubicSpline, interp1d
import sys
import concurrent.futures
import time
import json
import pickle
import gc
import warnings
warnings.filterwarnings("ignore")
# ================= 配置区域 =================
# !! 修改此处:指定包含ZIP文件的根目录
TARGET_FOLDER = r"C:\Users\Administrator\Desktop\denoise\data\100hz_c"
# !! 核心设置:光源选择
# 'green' : 绿光 (推荐,波形最清晰,对应你发的图片)
# 'ir' : 红外光 (穿透深,但易受干扰)
# 'fusion' : 绿光+红外光融合 (加权平均,抗噪性更好)
TARGET_LIGHT_TYPE = 'fusion'
# !! 核心设置:是否反转波形
# True : 波形向下扎 (收缩期为谷,对应你发的图片)
# False : 波形向上顶 (收缩期为峰,标准分析形态)
INVERT_SIGNAL = True
# 并行进程数
MAX_WORKERS = 4
# 是否保存中间过程 CSV
SAVE_EXTRA_FULL_DF = False
# 数据连续性与时长设置
MAX_ALLOWED_GAP_SECONDS = 3
MIN_SEGMENT_DURATION_SECONDS = 10
MAX_SEGMENT_DURATION_HOURS = 24
# --- 信号处理常量 ---
PPG_SAMPLING_RATE = 25 # 原始 PPG 采样率
ACC_SAMPLING_RATE = 100 # 原始 ACC 采样率
FILTERING_SAMPLING_RATE = 100 # 目标重采样率
# 滤波器设置 (0.8 - 8.0 Hz)
# 0.8Hz (48 BPM) 能有效去除身体晃动引起的低频噪声
PPG_LOWCUT = 0.8
PPG_HIGHCUT = 8.0
ACC_LOWPASS = 5.0
FILTER_ORDER = 4
# ===========================================
class BasicSignalProcessor:
"""
基础信号处理器:执行反转、带通滤波
"""
@staticmethod
def butter_bandpass_filter(data, lowcut, highcut, fs, order=4):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
sos = butter(order, [low, high], btype='band', output='sos')
return sosfiltfilt(sos, data)
@staticmethod
def butter_lowpass_filter(data, cutoff, fs, order=4):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
sos = butter(order, normal_cutoff, btype='low', output='sos')
return sosfiltfilt(sos, data)
@staticmethod
def process(df):
"""执行基础滤波流程"""
# 1. 预处理 ACC
acc_cols = ['ACC_X', 'ACC_Y', 'ACC_Z']
valid_acc_cols = [c for c in acc_cols if c in df.columns]
if len(valid_acc_cols) == 3:
acc_data = df[valid_acc_cols].values
acc_mag = np.linalg.norm(acc_data, axis=1, keepdims=True)
else:
acc_data = np.zeros((len(df), 3))
acc_mag = np.zeros((len(df), 1))
# 2. PPG 处理
# 填充 NaN
ppg_raw = df['PPG'].fillna(method='ffill').fillna(method='bfill').values
# === 极性反转 (关键步骤) ===
if INVERT_SIGNAL:
ppg_raw = -1 * ppg_raw
# =========================
# 带通滤波
ppg_filtered = BasicSignalProcessor.butter_bandpass_filter(
ppg_raw, PPG_LOWCUT, PPG_HIGHCUT, FILTERING_SAMPLING_RATE
)
# 3. ACC 低通滤波
acc_filtered_list = []
for i in range(3):
acc_filtered_list.append(
BasicSignalProcessor.butter_lowpass_filter(acc_data[:, i], ACC_LOWPASS, FILTERING_SAMPLING_RATE)
)
acc_mag_filtered = BasicSignalProcessor.butter_lowpass_filter(acc_mag.flatten(), ACC_LOWPASS, FILTERING_SAMPLING_RATE)
# 4. 存回 DataFrame
df['PPG_Filtered'] = ppg_filtered
df['ACC_X_Filtered'] = acc_filtered_list[0]
df['ACC_Y_Filtered'] = acc_filtered_list[1]
df['ACC_Z_Filtered'] = acc_filtered_list[2]
df['ACC_Mag_Filtered'] = acc_mag_filtered
return df
# ================= 数据读取与清洗 =================
def convert_txt_to_dataframe(txt_file_path):
try:
df = pd.read_csv(txt_file_path, sep='\t', on_bad_lines='warn', engine='c')
return df
except Exception as e:
print(f" -> [错误] 读取 '{os.path.basename(txt_file_path)}' 时发生错误: {e}")
return None
def separate_sensor_data(df):
try:
ppg_cols = [c for c in df.columns if c.startswith('PPG')]
ppg_df = df[ppg_cols].copy()
ppg_df = ppg_df[ppg_df['PPG_TIME'] > 0].reset_index(drop=True)
acc_cols = ['ACC_TIME', 'ACC_X', 'ACC_Y', 'ACC_Z']
acc_cols = [c for c in acc_cols if c in df.columns]
acc_df = df[acc_cols].copy()
acc_df = acc_df[acc_df['ACC_TIME'] > 0].reset_index(drop=True)
if ppg_df.empty:
return None, None
return ppg_df, acc_df
except Exception as e:
print(f" [错误] 分离数据: {e}")
return None, None
def select_best_ppg_channel(df, light_type='green'):
"""根据光源类型选择最佳通道"""
ppg_cols = [c for c in df.columns if c.startswith('PPG') and c != 'PPG_TIME']
valid_cols = [c for c in ppg_cols if df[c].any()]
# 通道映射
channel_map = {
'green': [3, 4, 5, 6, 7, 8, 18, 19, 20],
'ir': [1, 9, 10, 11, 15, 16, 17],
'red': [12, 13, 14]
}
target_indices = set(channel_map.get(light_type, []))
candidate_channels = [ch for ch in valid_cols if int(ch.replace('PPG', '')) in target_indices]
if not candidate_channels:
raise ValueError(f"未找到 {light_type} 类型的有效通道")
data_matrix = df[candidate_channels].to_numpy()
# 环境光消除
if 'PPG2' in df.columns:
ambient = df['PPG2'].to_numpy()
if np.any(ambient):
data_matrix = data_matrix - ambient[:, None]
# 峰度选择
k_scores = kurtosis(data_matrix, axis=0, fisher=False)
k_scores = np.nan_to_num(k_scores, nan=-np.inf)
best_idx = np.argmax(k_scores)
return pd.DataFrame({
'PPG_TIME': df['PPG_TIME'],
'PPG_Selected': data_matrix[:, best_idx]
})
def reconstruct_timestamps(df, time_col, sample_rate_hz):
interval_ms = 1000.0 / sample_rate_hz
group_sizes = df.groupby(time_col)[time_col].transform('size')
group_indices = df.groupby(time_col).cumcount()
offsets = (group_sizes - 1 - group_indices) * interval_ms
timestamps_ms = df[time_col] - offsets
df['Timestamp'] = pd.to_datetime(timestamps_ms, unit='ms')
return df
def _get_healthy_segments(df, time_col):
if df is None or df.empty: return []
df = df.sort_values('Timestamp').reset_index(drop=True)
time_diffs = df['Timestamp'].diff().dt.total_seconds()
break_indices = time_diffs[time_diffs > MAX_ALLOWED_GAP_SECONDS].index
if len(break_indices) > 0:
segments_raw = np.split(df, break_indices)
else:
segments_raw = [df]
healthy_segments = []
for seg in segments_raw:
if len(seg) < 2: continue
duration = (seg['Timestamp'].iloc[-1] - seg['Timestamp'].iloc[0]).total_seconds()
if duration >= MIN_SEGMENT_DURATION_SECONDS and duration <= MAX_SEGMENT_DURATION_HOURS * 3600:
healthy_segments.append(seg.copy())
return healthy_segments
# ================= 核心同步与融合逻辑 =================
def interpolate_signal(time_series, data_series, target_ts):
"""辅助插值函数"""
x = time_series.astype(np.int64).values / 1e9
y = data_series.values
if np.any(np.diff(x) <= 0):
_, u_idx = np.unique(x, return_index=True)
x, y = x[u_idx], y[u_idx]
try:
return CubicSpline(x, y)(target_ts)
except:
return interp1d(x, y, kind='linear', fill_value="extrapolate")(target_ts)
def process_and_synchronize(df_ppg_raw, df_acc_raw, mode='green'):
"""
统一处理函数:支持单通道(green/ir) 和 融合(fusion)
"""
# 1. 准备 PPG 数据源
sources = {}
try:
if mode == 'fusion':
sources['green'] = select_best_ppg_channel(df_ppg_raw, 'green')
sources['ir'] = select_best_ppg_channel(df_ppg_raw, 'ir')
else:
sources['main'] = select_best_ppg_channel(df_ppg_raw, mode)
except ValueError:
return [] # 缺少必要通道
# 2. 重建时间戳
for key in sources:
sources[key] = reconstruct_timestamps(sources[key], 'PPG_TIME', PPG_SAMPLING_RATE)
# 3. 准备 ACC
if df_acc_raw is not None and not df_acc_raw.empty:
df_acc_raw = reconstruct_timestamps(df_acc_raw, 'ACC_TIME', ACC_SAMPLING_RATE)
acc_segments = _get_healthy_segments(df_acc_raw, 'ACC_TIME')
else:
acc_segments = []
# 4. 分段 (以主信号为准)
main_key = 'green' if mode == 'fusion' else 'main'
ppg_segments = _get_healthy_segments(sources[main_key], 'PPG_TIME')
synced_segments = []
for ppg_seg in ppg_segments:
start_time = ppg_seg['Timestamp'].min()
end_time = ppg_seg['Timestamp'].max()
# 如果是融合模式,检查 IR 是否覆盖
if mode == 'fusion':
ir_df = sources['ir']
ir_subset = ir_df[(ir_df['Timestamp'] >= start_time) & (ir_df['Timestamp'] <= end_time)]
if len(ir_subset) < len(ppg_seg) * 0.9: continue
# 寻找 ACC
best_acc_seg = None
if acc_segments:
for acc_seg in acc_segments:
if (acc_seg['Timestamp'].max() > start_time) and (acc_seg['Timestamp'].min() < end_time):
best_acc_seg = acc_seg
break
# 生成目标时间轴
target_freq = '10ms'
target_index = pd.date_range(start=start_time, end=end_time, freq=target_freq)
if len(target_index) < 2: continue
target_ts_float = target_index.astype(np.int64) / 1e9
# === 插值与融合 ===
if mode == 'fusion':
# 插值两路信号
green_interp = interpolate_signal(ppg_seg['Timestamp'], ppg_seg['PPG_Selected'], target_ts_float)
ir_interp = interpolate_signal(ir_subset['Timestamp'], ir_subset['PPG_Selected'], target_ts_float)
# Z-Score 归一化后平均
def z_score(arr):
std = np.std(arr)
return (arr - np.mean(arr)) / (std if std > 0 else 1)
ppg_final = (z_score(green_interp) + z_score(ir_interp)) / 2.0
else:
# 单通道插值
ppg_final = interpolate_signal(ppg_seg['Timestamp'], ppg_seg['PPG_Selected'], target_ts_float)
# ACC 插值
acc_data_interp = {}
if best_acc_seg is not None:
for col in ['ACC_X', 'ACC_Y', 'ACC_Z']:
acc_data_interp[col] = interpolate_signal(best_acc_seg['Timestamp'], best_acc_seg[col], target_ts_float)
else:
zeros = np.zeros(len(target_index))
acc_data_interp = {'ACC_X': zeros, 'ACC_Y': zeros, 'ACC_Z': zeros}
final_data = {'Timestamp': target_index, 'PPG': ppg_final}
final_data.update(acc_data_interp)
synced_segments.append(pd.DataFrame(final_data))
return synced_segments
def process_dataframe_to_pkl(input_df, output_pkl_path_base, uid_str):
"""执行流程并保存"""
ppg_raw, acc_raw = separate_sensor_data(input_df)
if ppg_raw is None: raise RuntimeError("无PPG数据")
# 调用统一处理函数
list_of_sync_df = process_and_synchronize(ppg_raw, acc_raw, mode=TARGET_LIGHT_TYPE)
if not list_of_sync_df:
raise RuntimeError("未找到有效片段")
processed_metadata = []
for i, sync_df in enumerate(list_of_sync_df):
duration = (sync_df['Timestamp'].max() - sync_df['Timestamp'].min()).total_seconds()
if duration < MIN_SEGMENT_DURATION_SECONDS: continue
part_uid = f"{uid_str}_part_{i}"
output_pkl_path = output_pkl_path_base.replace('.pkl', f'_part_{i}.pkl')
# 滤波 + 反转
final_df = BasicSignalProcessor.process(sync_df)
# 保存
target_col = 'PPG_Filtered'
data_array = final_df[target_col].fillna(0).to_numpy().reshape(1, -1)
output_data = {
'uid': part_uid,
'data': data_array,
'fs': FILTERING_SAMPLING_RATE,
'light_type': TARGET_LIGHT_TYPE,
'inverted': INVERT_SIGNAL
}
with open(output_pkl_path, 'wb') as f:
pickle.dump(output_data, f)
if SAVE_EXTRA_FULL_DF:
extra_output_path = output_pkl_path.replace('.pkl', '_full.csv')
final_df.to_csv(extra_output_path, index=False)
processed_metadata.append({
"output_filename": os.path.basename(output_pkl_path),
"uid": part_uid,
"light_type": TARGET_LIGHT_TYPE
})
return processed_metadata
def process_single_zip_task(zip_file_path, current_folder):
"""处理单个ZIP文件"""
base_name = os.path.basename(zip_file_path)
zip_name_without_ext, _ = os.path.splitext(base_name)
extract_path = os.path.join(current_folder, f"temp_{os.getpid()}_{int(time.time())}")
if os.path.exists(extract_path): shutil.rmtree(extract_path)
os.makedirs(extract_path)
time_metadata = {}
total_segments_count = 0
try:
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
zip_ref.extractall(extract_path)
for root, _, files in os.walk(extract_path):
for file in files:
if file.lower().endswith('.txt'):
txt_path = os.path.join(root, file)
file_no_ext = os.path.splitext(file)[0]
uid_str = f"{zip_name_without_ext}_{file_no_ext}"
output_path_base = os.path.join(current_folder, f"{uid_str}_processed.pkl")
try:
df = convert_txt_to_dataframe(txt_path)
if df is not None:
list_of_meta = process_dataframe_to_pkl(df, output_path_base, uid_str)
for meta in list_of_meta:
time_metadata[meta.pop("output_filename")] = meta
total_segments_count += len(list_of_meta)
except Exception as e:
pass
del df
gc.collect()
except Exception as e:
return f"ZIP错误: {e}", {}
finally:
if os.path.exists(extract_path): shutil.rmtree(extract_path)
try: os.remove(zip_file_path)
except: pass
return f"完成 {base_name}: {total_segments_count} 片段", time_metadata
def main():
start_time = time.time()
abs_target_folder = os.path.abspath(TARGET_FOLDER)
if not os.path.isdir(abs_target_folder):
print(f"错误:路径不存在 {abs_target_folder}")
return
zip_tasks = []
for root, dirs, files in os.walk(abs_target_folder):
for file in files:
if file.lower().endswith('.zip'):
zip_tasks.append((os.path.join(root, file), root))
if not zip_tasks:
print("未找到ZIP文件。")
return
print(f"发现 {len(zip_tasks)} 个ZIP。")
print(f"模式: {TARGET_LIGHT_TYPE.upper()} | 反转: {INVERT_SIGNAL} | Workers: {MAX_WORKERS}")
all_metadata = {}
with concurrent.futures.ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
futures = {executor.submit(process_single_zip_task, p, d): p for p, d in zip_tasks}
for i, future in enumerate(concurrent.futures.as_completed(futures)):
try:
msg, meta = future.result()
print(f"[{i+1}/{len(zip_tasks)}] {msg}")
all_metadata.update(meta)
except Exception as exc:
print(f"任务异常: {exc}")
if all_metadata:
with open(os.path.join(abs_target_folder, "pkl_metadata_summary.json"), 'w', encoding='utf-8') as f:
json.dump(all_metadata, f, indent=4, ensure_ascii=False)
print(f"总耗时: {time.time() - start_time:.2f} 秒")
if __name__ == "__main__":
main()