California_ISO / scripts /merge_embed.py
Xu Zhijian
init commit
c2786b1
import os
import sys
import glob
import joblib
import numpy as np
from tqdm import tqdm
def merge_and_stack_folders(folder1_path, folder2_path, output_dir):
"""
Merge same-name .pkl files from two folders and stack their contents by timestamp.
"""
# 1. Validate existence of input paths
if not os.path.isdir(folder1_path):
print(f"Error: Folder not found -> {folder1_path}")
return
if not os.path.isdir(folder2_path):
print(f"Error: Folder not found -> {folder2_path}")
return
# 2. Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
print(f"Input folder 1: {folder1_path}")
print(f"Input folder 2: {folder2_path}")
print(f"Output will be saved to: {output_dir}")
# 3. Find all .pkl files in first folder
folder1_files = glob.glob(os.path.join(folder1_path, "*.pkl"))
if not folder1_files:
print(f"Warning: No .pkl files found in {folder1_path}.")
return
print(f"\nFound {len(folder1_files)} files, starting pairwise merging...")
# 4. Traverse files, find pairs and process
for file1_path in tqdm(folder1_files, desc="Processing file pairs"):
file_name = os.path.basename(file1_path)
file2_path = os.path.join(folder2_path, file_name)
# Check if paired file exists in second folder
if not os.path.exists(file2_path):
print(f"\nSkipped: Paired file not found in {folder2_path} for {file_name}")
continue
try:
# Load data from both files
with open(file1_path, 'rb') as f:
data1 = joblib.load(f)
with open(file2_path, 'rb') as f:
data2 = joblib.load(f)
except Exception as e:
print(f"\nError: Failed to load file pair {file_name}: {e}")
continue
# Create new dictionary for merged data
merged_data = {}
# Find common timestamps (keys) in both dictionaries
common_keys = data1.keys() & data2.keys()
for key in common_keys:
vec1 = data1[key]
vec2 = data2[key]
# Verify vectors meet expectations
if isinstance(vec1, np.ndarray) and isinstance(vec2, np.ndarray) and \
vec1.ndim == 2 and vec2.ndim == 2 and \
vec1.shape[1] == vec2.shape[1]: # Ensure same number of columns
# Vertically stack (N, D) and (M, D) -> (N+M, D)
# Example: (7, 256) and (7, 256) -> (14, 256)
stacked_vec = np.vstack((vec1, vec2))
merged_data[key] = stacked_vec
else:
print(f"\nWarning: Data format mismatch at timestamp {key} in file {file_name}, skipped.")
# Save result if any data was successfully merged
if merged_data:
output_path = os.path.join(output_dir, file_name)
try:
with open(output_path, 'wb') as f:
joblib.dump(merged_data, f)
except Exception as e:
print(f"\nError: Failed to save merged file {output_path}: {e}")
def main():
"""
Main execution function.
"""
folder1 = "./data/California_ISO/weather/san-francisco"
folder2 = "./data/California_ISO/weather/san-diego"
output_folder = "./data/California_ISO/weather/merged_report_embedding"
merge_and_stack_folders(folder1, folder2, output_folder)
print("\nAll matching files merged and stacked successfully!")
if __name__ == "__main__":
main()