Files
2025-10-30 17:52:46 +08:00

254 lines
10 KiB
Python

# this file is used to combining ppg and ecg signal file
import os
import pickle
import numpy as np
from tqdm import tqdm
import sys
import concurrent.futures
import traceback
from typing import Dict, List, Tuple, Any, Optional
import collections
# --- 常量和配置 (无变化) ---
FOLDER1_PATH = r'/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/ecg_full'
FOLDER2_PATH = r'/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/ppg_full'
COMMON_TIMESTAMPS_FILE = 'common1.txt'
OUTPUT_BASE_NAME = 'combined_processed_data_2d'
OUTPUT_FOLDER = r'/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/full_data'
TIMESTAMP_LIMIT: Optional[int] = None
CHUNK_SIZE = 20
# 保持较低的进程数以避免内存问题
NUM_PROCESSES: Optional[int] = 2
WORKER_CACHE_SIZE = 10
TIMESTAMP_KEY = 'timestamp'
DATA_KEY = 'data'
# --- 全局变量 (无变化) ---
worker_index1: Optional[Dict[Any, Tuple[str, int]]] = None
worker_index2: Optional[Dict[Any, Tuple[str, int]]] = None
_worker_file_cache: Optional[collections.OrderedDict[str,
List[Dict[str, Any]]]] = None
# --- 索引构建、读取Timestamp、降采样、Worker初始化、缓存加载函数 (均无变化) ---
def build_timestamp_index(folder_path: str, description: str) -> Dict[Any, Tuple[str, int]]:
timestamp_index: Dict[Any, Tuple[str, int]] = {}
if not os.path.isdir(folder_path):
print(f"错误:索引构建失败,文件夹未找到或不是一个目录:{folder_path}", file=sys.stderr)
return timestamp_index
all_files = [f for f in os.listdir(folder_path) if f.endswith('.pkl')]
print(f"开始构建索引 for {description}...")
for filename in tqdm(all_files, desc=description, unit="file"):
file_path = os.path.join(folder_path, filename)
try:
with open(file_path, 'rb') as f:
data_list = pickle.load(f)
if isinstance(data_list, list):
for i, item in enumerate(data_list):
if isinstance(item, dict) and TIMESTAMP_KEY in item:
ts = item[TIMESTAMP_KEY]
timestamp_index[ts] = (file_path, i)
except Exception as e:
print(f"索引构建处理文件 {file_path} 时发生错误:{e}", file=sys.stderr)
return timestamp_index
def read_common_timestamps(file_path: str) -> List[Any]:
common_timestamps: List[Any] = []
if not os.path.exists(file_path):
print(f"错误:未找到共有的 timestamp 文件:{file_path}", file=sys.stderr)
return common_timestamps
print(f"正在读取共有的 timestamp 文件:{file_path}")
try:
with open(file_path, 'r') as f:
for line in tqdm(f, desc="读取 timestamp", unit="line"):
ts_str = line.strip()
if ts_str:
common_timestamps.append(ts_str)
except Exception as e:
print(f"读取共有的 timestamp 文件时发生错误:{e}", file=sys.stderr)
return common_timestamps
def downsample_multidim(data: np.ndarray, target_length: int, axis: int = 0) -> np.ndarray:
current_length = data.shape[axis]
if current_length == target_length:
return data
if target_length <= 0:
return np.empty((*data.shape[:axis], 0, *data.shape[axis+1:]), dtype=data.dtype)
indices = np.linspace(0, current_length - 1, target_length, dtype=int)
return np.take(data, indices, axis=axis)
def worker_init(idx1: Dict[Any, Tuple[str, int]], idx2: Dict[Any, Tuple[str, int]]):
global worker_index1, worker_index2, _worker_file_cache
worker_index1 = idx1
worker_index2 = idx2
_worker_file_cache = collections.OrderedDict()
def load_data_from_file_cached(file_path: str) -> Optional[List[Dict[str, Any]]]:
global _worker_file_cache, WORKER_CACHE_SIZE
if _worker_file_cache is None:
return None
if file_path in _worker_file_cache:
data_list = _worker_file_cache.pop(file_path)
_worker_file_cache[file_path] = data_list
return data_list
else:
try:
with open(file_path, 'rb') as f:
data_list = pickle.load(f)
_worker_file_cache[file_path] = data_list
if len(_worker_file_cache) > WORKER_CACHE_SIZE:
_worker_file_cache.popitem(last=False)
return data_list
except Exception as e:
print(f"Worker缓存加载失败 {file_path}: {e}", file=sys.stderr)
return None
# --- 核心处理函数 (已修改) ---
def process_single_timestamp(ts: Any) -> Optional[Dict[str, Any]]:
global worker_index1, worker_index2
if worker_index1 is None or worker_index2 is None:
raise RuntimeError(f"Worker索引未初始化")
location1 = worker_index1.get(ts)
location2 = worker_index2.get(ts)
if not location1 or not location2:
return None
file1_path, index1 = location1
file2_path, index2 = location2
data1_list = load_data_from_file_cached(file1_path)
data2_list = load_data_from_file_cached(file2_path)
if not data1_list or not data2_list:
return None
try:
item1 = data1_list[index1]
item2 = data2_list[index2]
# 确保ECG是一维数组 (length,)
ecg_data = item1[DATA_KEY].flatten()
ppg_acc_data = item2[DATA_KEY]
# --- 关键修改:检查并修正PPG/ACC数据的方向 ---
# 假设通道数(4)远小于信号长度
# 如果形状是 (4, length),则进行转置
if ppg_acc_data.ndim == 2 and ppg_acc_data.shape[0] < ppg_acc_data.shape[1]:
# 这是一个很好的指示,说明数据是 (channels, length) 格式
# 我们需要的是 (length, channels)
ppg_acc_data = ppg_acc_data.T # 转置操作
# --- 修改结束 ---
# 现在可以安全地假设 ppg_acc_data 的形状是 (length, 4)
ecg_len = len(ecg_data)
ppg_acc_len = ppg_acc_data.shape[0]
target_length = min(ecg_len, ppg_acc_len)
if ecg_len > target_length:
ecg_data = downsample_multidim(ecg_data, target_length, axis=0)
if ppg_acc_len > target_length:
# 降采样是沿着 axis=0 (长度维度) 进行的
ppg_acc_data = downsample_multidim(
ppg_acc_data, target_length, axis=0)
# 分离 PPG 和 ACC (现在这个切片逻辑是安全的)
ppg = ppg_acc_data[:, 0] # 第1列是PPG
acc = ppg_acc_data[:, 1:4] # 第2到4列是ACC
# 合并为 (5, length)
# np.stack 会将一系列一维数组堆叠成一个二维数组
combined = np.stack([
ecg_data.astype(np.float32), # 形状: (target_length,)
ppg.astype(np.float32), # 形状: (target_length,)
acc[:, 0].astype(np.float32), # 形状: (target_length,)
acc[:, 1].astype(np.float32), # 形状: (target_length,)
acc[:, 2].astype(np.float32) # 形状: (target_length,)
], axis=0) # axis=0 使它们成为行,最终形状 (5, target_length)
return {TIMESTAMP_KEY: ts, DATA_KEY: combined}
except Exception as e:
print(f"处理 {ts} 时发生错误 (文件: {file1_path}, {file2_path}): {e}",
file=sys.stderr)
traceback.print_exc()
return None
# --- 主程序 (无变化) ---
if __name__ == '__main__':
print("--- 开始处理 (使用降采样,自动修正数据方向) ---")
common_ts = read_common_timestamps(COMMON_TIMESTAMPS_FILE)
if TIMESTAMP_LIMIT:
common_ts = common_ts[:TIMESTAMP_LIMIT]
index1 = build_timestamp_index(FOLDER1_PATH, "ECG索引")
index2 = build_timestamp_index(FOLDER2_PATH, "PPG索引")
if not index1 or not index2:
sys.exit()
valid_ts = []
for ts in common_ts:
if ts in index1 and ts in index2:
valid_ts.append(ts)
valid_ts.sort(key=lambda x: (index1[x][0], index2[x][0], x))
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
chunk = []
chunk_num = 1
processed = 0
try:
with concurrent.futures.ProcessPoolExecutor(
max_workers=NUM_PROCESSES,
initializer=worker_init,
initargs=(index1, index2)
) as executor:
futures = {executor.submit(
process_single_timestamp, ts): ts for ts in valid_ts}
for future in tqdm(concurrent.futures.as_completed(futures), total=len(valid_ts), desc="处理中"):
ts = futures[future]
try:
result = future.result()
if result:
# 验证一下输出形状 (可选,但有助于调试)
if result[DATA_KEY].shape[0] != 5:
print(
f"警告:时间戳 {ts} 的输出形状不正确: {result[DATA_KEY].shape}", file=sys.stderr)
continue
chunk.append(result)
processed += 1
if len(chunk) >= CHUNK_SIZE:
output_path = os.path.join(
OUTPUT_FOLDER, f"{OUTPUT_BASE_NAME}_part{chunk_num:03d}.pkl")
with open(output_path, 'wb') as f:
pickle.dump(chunk, f)
chunk = []
chunk_num += 1
except Exception as e:
print(f"处理 {ts} 的 future 时严重失败: {e}")
except concurrent.futures.process.BrokenProcessPool:
print("\n错误:进程池已损坏。通常是由于内存不足。请尝试将 NUM_PROCESSES 减小到 1。", file=sys.stderr)
if chunk:
output_path = os.path.join(
OUTPUT_FOLDER, f"{OUTPUT_BASE_NAME}_part{chunk_num:03d}.pkl")
with open(output_path, 'wb') as f:
pickle.dump(chunk, f)
print(f"处理完成!成功处理 {processed} 条数据,保存为 {chunk_num} 个文件。")