|
| 1 | +use anyhow::Result; |
| 2 | +use clap::Parser; |
| 3 | +use sprite_video_renderer::data::{ParquetFilter, ParquetReader, SpriteFrame}; |
| 4 | +use std::collections::HashMap; |
| 5 | +use std::path::PathBuf; |
| 6 | + |
| 7 | +#[derive(Parser, Debug)] |
| 8 | +#[command(author, version, about = "Analyze user+env_id runs in parquet file", long_about = None)] |
| 9 | +struct Args { |
| 10 | + /// Path to parquet file |
| 11 | + #[arg(long)] |
| 12 | + parquet_file: PathBuf, |
| 13 | +} |
| 14 | + |
| 15 | +#[derive(Debug)] |
| 16 | +struct Run { |
| 17 | + start_timestamp: chrono::DateTime<chrono::Utc>, |
| 18 | + end_timestamp: chrono::DateTime<chrono::Utc>, |
| 19 | + coord_count: usize, |
| 20 | +} |
| 21 | + |
| 22 | +#[derive(Debug)] |
| 23 | +struct UserEnvStats { |
| 24 | + user: String, |
| 25 | + env_id: String, |
| 26 | + runs: Vec<Run>, |
| 27 | + total_coords: usize, |
| 28 | +} |
| 29 | + |
| 30 | +fn main() -> Result<()> { |
| 31 | + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); |
| 32 | + |
| 33 | + let args = Args::parse(); |
| 34 | + |
| 35 | + log::info!("=== Analyzing runs in parquet file ==="); |
| 36 | + log::info!("Parquet file: {:?}", args.parquet_file); |
| 37 | + |
| 38 | + // Read all frames from parquet |
| 39 | + log::info!("Reading parquet file..."); |
| 40 | + let reader = ParquetReader::new(ParquetFilter::default()); |
| 41 | + let frames = reader.read_file(&args.parquet_file)?; |
| 42 | + |
| 43 | + log::info!("Total frames read: {}", frames.len()); |
| 44 | + |
| 45 | + // Group by user+env_id directly and build run splits in one pass |
| 46 | + log::info!("Grouping and detecting runs..."); |
| 47 | + let mut user_env_data: HashMap<String, Vec<SpriteFrame>> = HashMap::new(); |
| 48 | + |
| 49 | + for frame in frames { |
| 50 | + let key = format!("{}-{}", frame.user, frame.env_id); |
| 51 | + user_env_data.entry(key).or_insert_with(Vec::new).push(frame); |
| 52 | + } |
| 53 | + |
| 54 | + log::info!("Found {} unique user+env_id pairs", user_env_data.len()); |
| 55 | + |
| 56 | + // Process each user+env_id to identify runs with reset detection |
| 57 | + let mut stats: Vec<UserEnvStats> = Vec::new(); |
| 58 | + let reset_maps = vec![0i64, 37, 40]; |
| 59 | + |
| 60 | + for (_key, mut frames_list) in user_env_data { |
| 61 | + if frames_list.is_empty() { |
| 62 | + continue; |
| 63 | + } |
| 64 | + |
| 65 | + // Sort by timestamp |
| 66 | + frames_list.sort_by_key(|f| (f.timestamp, f.path_index)); |
| 67 | + |
| 68 | + let user = frames_list[0].user.clone(); |
| 69 | + let env_id = frames_list[0].env_id.clone(); |
| 70 | + let total_coords = frames_list.len(); |
| 71 | + |
| 72 | + // Detect runs with 2-minute gaps and reset events |
| 73 | + let runs = detect_runs_with_resets(&frames_list, &reset_maps); |
| 74 | + |
| 75 | + stats.push(UserEnvStats { |
| 76 | + user, |
| 77 | + env_id, |
| 78 | + runs, |
| 79 | + total_coords, |
| 80 | + }); |
| 81 | + } |
| 82 | + |
| 83 | + // Filter out runs < 60 seconds |
| 84 | + let min_duration = chrono::Duration::seconds(60); |
| 85 | + let mut total_runs_before = 0; |
| 86 | + for stat in &mut stats { |
| 87 | + total_runs_before += stat.runs.len(); |
| 88 | + stat.runs.retain(|run| { |
| 89 | + (run.end_timestamp - run.start_timestamp) >= min_duration |
| 90 | + }); |
| 91 | + } |
| 92 | + |
| 93 | + log::info!("Runs before 60s filter: {}", total_runs_before); |
| 94 | + log::info!("Runs after 60s filter: {}", stats.iter().map(|s| s.runs.len()).sum::<usize>()); |
| 95 | + |
| 96 | + // Remove user+env_id pairs with no runs left after filtering |
| 97 | + stats.retain(|s| !s.runs.is_empty()); |
| 98 | + |
| 99 | + // Recalculate total coords after filtering |
| 100 | + for stat in &mut stats { |
| 101 | + stat.total_coords = stat.runs.iter().map(|r| r.coord_count).sum(); |
| 102 | + } |
| 103 | + |
| 104 | + // Sort by total coords descending for easier reading |
| 105 | + stats.sort_by_key(|s| std::cmp::Reverse(s.total_coords)); |
| 106 | + |
| 107 | + // Print summary |
| 108 | + println!("\n=== SUMMARY (after filtering runs < 60s) ==="); |
| 109 | + println!("Total unique user+env_id pairs: {}", stats.len()); |
| 110 | + println!("Total runs across all pairs: {}", stats.iter().map(|s| s.runs.len()).sum::<usize>()); |
| 111 | + println!(); |
| 112 | + |
| 113 | + // Print detailed stats (limit to first 50 to avoid huge output) |
| 114 | + println!("=== DETAILED BREAKDOWN (top 50) ===\n"); |
| 115 | + |
| 116 | + for stat in stats.iter().take(50) { |
| 117 | + println!("User: {}, Env ID: {}", stat.user, stat.env_id); |
| 118 | + println!(" Total coords: {}", stat.total_coords); |
| 119 | + println!(" Number of runs: {}", stat.runs.len()); |
| 120 | + |
| 121 | + for (i, run) in stat.runs.iter().enumerate() { |
| 122 | + let duration = run.end_timestamp - run.start_timestamp; |
| 123 | + println!(" Run {}: {} coords, duration: {:.1}s ({} to {})", |
| 124 | + i + 1, |
| 125 | + run.coord_count, |
| 126 | + duration.num_milliseconds() as f64 / 1000.0, |
| 127 | + run.start_timestamp.format("%Y-%m-%d %H:%M:%S"), |
| 128 | + run.end_timestamp.format("%Y-%m-%d %H:%M:%S")); |
| 129 | + } |
| 130 | + println!(); |
| 131 | + } |
| 132 | + |
| 133 | + Ok(()) |
| 134 | +} |
| 135 | + |
| 136 | +/// Detect runs based on 2-minute gaps and reset events |
| 137 | +/// This processes frames in a single pass - O(n) |
| 138 | +fn detect_runs_with_resets( |
| 139 | + frames: &[SpriteFrame], |
| 140 | + reset_maps: &[i64], |
| 141 | +) -> Vec<Run> { |
| 142 | + if frames.is_empty() { |
| 143 | + return Vec::new(); |
| 144 | + } |
| 145 | + |
| 146 | + let mut runs = Vec::new(); |
| 147 | + let gap_threshold = chrono::Duration::minutes(2); |
| 148 | + |
| 149 | + let mut run_start_idx = 0; |
| 150 | + |
| 151 | + for i in 1..frames.len() { |
| 152 | + let time_gap = frames[i].timestamp - frames[i-1].timestamp; |
| 153 | + let curr_map = frames[i].coords[2]; |
| 154 | + let prev_map = frames[i-1].coords[2]; |
| 155 | + |
| 156 | + let mut should_split = false; |
| 157 | + |
| 158 | + // Split on 2-minute gaps |
| 159 | + if time_gap >= gap_threshold { |
| 160 | + should_split = true; |
| 161 | + } |
| 162 | + |
| 163 | + // Split when jumping TO a reset map (0, 37, 40) from a different map |
| 164 | + if reset_maps.contains(&curr_map) && !reset_maps.contains(&prev_map) { |
| 165 | + should_split = true; |
| 166 | + } |
| 167 | + |
| 168 | + if should_split { |
| 169 | + let run = Run { |
| 170 | + start_timestamp: frames[run_start_idx].timestamp, |
| 171 | + end_timestamp: frames[i-1].timestamp, |
| 172 | + coord_count: i - run_start_idx, |
| 173 | + }; |
| 174 | + runs.push(run); |
| 175 | + run_start_idx = i; |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + // Add the final run |
| 180 | + let final_run = Run { |
| 181 | + start_timestamp: frames[run_start_idx].timestamp, |
| 182 | + end_timestamp: frames[frames.len() - 1].timestamp, |
| 183 | + coord_count: frames.len() - run_start_idx, |
| 184 | + }; |
| 185 | + runs.push(final_run); |
| 186 | + |
| 187 | + runs |
| 188 | +} |
0 commit comments