File size: 3,151 Bytes
e0914bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
from tqdm import tqdm

def verify_trajectory_frequency(file_path):
    """
    验证轨迹数据是否为每分钟一个点。

    Args:
        file_path (str): 轨迹数据文件路径。
    """
    print(f"正在验证文件: {file_path}")
    
    try:
        df = pd.read_csv(file_path)
    except FileNotFoundError:
        print(f"❌ 错误:文件未找到 -> {file_path}")
        print("请先确保 'prepare_data.py' 脚本已成功运行并生成了 'matched_trajectory_data.csv' 文件。")
        return

    if 'datetime' not in df.columns or 'date' not in df.columns or 'userid' not in df.columns:
        print(f"❌ 错误:文件中缺少 'datetime', 'date', 或 'userid' 列。实际列: {df.columns.tolist()}")
        return
    
    # 转换数据类型
    df['datetime'] = pd.to_datetime(df['datetime'])
    
    # 按用户和日期分组
    grouped = df.groupby(['userid', 'date'])
    
    total_groups = len(grouped)
    inconsistent_groups = []
    
    print(f"总共找到 {total_groups} 个用户-日期组合,正在逐一检查...")
    
    for (userid, date), group in tqdm(grouped, total=total_groups, desc="检查时间频率"):
        # 按时间排序
        group_sorted = group.sort_values('datetime')
        
        # 计算时间差
        time_diffs = group_sorted['datetime'].diff().dropna()
        
        # 检查是否所有时间差都是1分钟
        # 使用 isclose 允许微小的浮点数误差
        is_consistent = all(pd.Timedelta(minutes=1) - pd.Timedelta(seconds=1) < diff < pd.Timedelta(minutes=1) + pd.Timedelta(seconds=1) for diff in time_diffs)
        
        if not is_consistent:
            # 记录不一致的组和详细信息
            non_one_minute_diffs = time_diffs[~time_diffs.apply(lambda x: pd.Timedelta(minutes=1) - pd.Timedelta(seconds=1) < x < pd.Timedelta(minutes=1) + pd.Timedelta(seconds=1))]
            inconsistent_groups.append({
                'userid': userid,
                'date': date,
                'details': non_one_minute_diffs.to_dict()
            })

    print("\\n" + "="*50)
    print("      验证结果")
    print("="*50)
    
    if not inconsistent_groups:
        print(f"✅ 验证通过!")
        print(f"所有 {total_groups} 个用户-日期组合的轨迹数据都严格遵循 '一分钟一个点' 的格式。")
    else:
        print(f"⚠️ 验证失败!发现 {len(inconsistent_groups)} 个用户-日期组合的时间频率不一致。")
        print("以下是前5个不一致组的详细信息:")
        for i, group_info in enumerate(inconsistent_groups[:5]):
            print(f"\\n  --- 示例 {i+1} ---")
            print(f"  - 用户ID: {group_info['userid']}, 日期: {group_info['date']}")
            for time_index, diff in list(group_info['details'].items())[:3]: # 只显示前3个异常
                timestamp = df.loc[time_index, 'datetime']
                print(f"    - 在时间点 {timestamp}, 检测到异常时间差: {diff}")
    
    print("="*50)

if __name__ == "__main__":
    verify_trajectory_frequency('data/matched_trajectory_data.csv')