386 lines
12 KiB
Rust
386 lines
12 KiB
Rust
use std::fs;
|
||
use std::path::PathBuf;
|
||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||
|
||
use clap::{Parser, Subcommand, ValueEnum};
|
||
|
||
use pp_jobboard_sim::generator::{BoardScratch, generate_board, partition_and_sort};
|
||
use pp_jobboard_sim::model::{BoardOptions, FilterMode, Plane, SortMode, WorldData};
|
||
use pp_jobboard_sim::rng::{board_salt, bucket_of, day_of, shop_salt};
|
||
use pp_jobboard_sim::sim::{ExportMode, SimConfig, run_simulation};
|
||
use pp_jobboard_sim::synthetic::{generate_synthetic_world, load_ourairports_csv};
|
||
use pp_jobboard_sim::world::WorldIndex;
|
||
|
||
#[derive(Parser)]
|
||
#[command(
|
||
name = "pp-jobboard-sim",
|
||
about = "High-throughput offline deterministic aviation job-board generator and balance simulator"
|
||
)]
|
||
struct Cli {
|
||
/// Path to world JSON (airports, majors, pads, sea_bases, sights, planes)
|
||
#[arg(long, global = true)]
|
||
world: Option<PathBuf>,
|
||
|
||
/// Path to OurAirports airports.csv (alternative to --world)
|
||
#[arg(long, global = true)]
|
||
ourairports: Option<PathBuf>,
|
||
|
||
/// Path to external planes JSON (overrides planes in world/synthetic)
|
||
#[arg(long, global = true)]
|
||
planes_file: Option<PathBuf>,
|
||
|
||
/// Number of synthetic global airports to generate if neither --world nor --ourairports is set
|
||
#[arg(long, global = true, default_value_t = 4000)]
|
||
synthetic_airports: usize,
|
||
|
||
/// Seed for synthetic world generation
|
||
#[arg(long, global = true, default_value_t = 42)]
|
||
world_seed: u32,
|
||
|
||
#[command(subcommand)]
|
||
cmd: Command,
|
||
}
|
||
|
||
#[derive(Clone, Copy, ValueEnum)]
|
||
enum CliExportMode {
|
||
Stats,
|
||
Csv,
|
||
Ndjson,
|
||
}
|
||
|
||
#[derive(Clone, Copy, ValueEnum)]
|
||
enum CliSort {
|
||
NetPerHour,
|
||
GrossPay,
|
||
FlightTime,
|
||
}
|
||
|
||
#[derive(Subcommand)]
|
||
enum Command {
|
||
/// Generate a job board for a single airport and plane set
|
||
Board {
|
||
/// Airport ICAO/code
|
||
#[arg(long)]
|
||
airport: String,
|
||
|
||
/// Comma-separated plane type IDs (e.g. light_piston,skyliner)
|
||
#[arg(long, alias = "fleet")]
|
||
planes: String,
|
||
|
||
/// Offline master seed string
|
||
#[arg(long, default_value = "offline")]
|
||
master: String,
|
||
|
||
/// Explicit uint32 board salt (overrides --master derivation)
|
||
#[arg(long)]
|
||
salt: Option<u32>,
|
||
|
||
/// Explicit uint32 daily shop salt
|
||
#[arg(long)]
|
||
day_salt: Option<u32>,
|
||
|
||
/// Epoch timestamp in milliseconds (defaults to current time)
|
||
#[arg(long)]
|
||
at: Option<i64>,
|
||
|
||
/// Airport level (0..=3)
|
||
#[arg(long, default_value_t = 0)]
|
||
level: u8,
|
||
|
||
/// Output raw JSON
|
||
#[arg(long)]
|
||
json: bool,
|
||
|
||
/// Apply presentation partitioning (ok/off/no) for the first plane
|
||
#[arg(long)]
|
||
partition: bool,
|
||
|
||
/// Sort order when --partition is enabled
|
||
#[arg(long, value_enum, default_value_t = CliSort::NetPerHour)]
|
||
sort: CliSort,
|
||
},
|
||
|
||
/// Run a multi-core global simulation across airports × buckets × planes
|
||
Sim {
|
||
/// Comma-separated plane IDs (defaults to all loaded planes)
|
||
#[arg(long)]
|
||
planes: Option<String>,
|
||
|
||
/// Offline master seed string
|
||
#[arg(long, default_value = "offline")]
|
||
master: String,
|
||
|
||
/// Explicit uint32 board salt (if set, reused for all buckets)
|
||
#[arg(long)]
|
||
salt: Option<u32>,
|
||
|
||
/// Starting epoch timestamp in milliseconds
|
||
#[arg(long, default_value_t = 1_796_067_000_000)]
|
||
at: i64,
|
||
|
||
/// Number of 30-minute buckets to simulate per airport
|
||
#[arg(long, default_value_t = 48)]
|
||
buckets: usize,
|
||
|
||
/// Airport level (0..=3)
|
||
#[arg(long, default_value_t = 0)]
|
||
level: u8,
|
||
|
||
/// Limit number of airports simulated
|
||
#[arg(long)]
|
||
airports: Option<usize>,
|
||
|
||
/// Output mode: stats (in-memory analytics), csv, or ndjson
|
||
#[arg(long, value_enum, default_value_t = CliExportMode::Stats)]
|
||
mode: CliExportMode,
|
||
|
||
/// Output file path (for csv or ndjson mode)
|
||
#[arg(long)]
|
||
out: Option<PathBuf>,
|
||
|
||
/// Print full JSON report
|
||
#[arg(long)]
|
||
json: bool,
|
||
},
|
||
}
|
||
|
||
fn load_world(cli: &Cli, precompute_neighbors: bool) -> WorldIndex {
|
||
let mut data: WorldData = if let Some(ref p) = cli.world {
|
||
let txt = fs::read_to_string(p).expect("failed to read --world file");
|
||
serde_json::from_str(&txt).expect("failed to parse --world JSON")
|
||
} else if let Some(ref p) = cli.ourairports {
|
||
load_ourairports_csv(p).expect("failed to load --ourairports CSV")
|
||
} else {
|
||
generate_synthetic_world(cli.world_seed, cli.synthetic_airports)
|
||
};
|
||
|
||
if let Some(ref pf) = cli.planes_file {
|
||
let txt = fs::read_to_string(pf).expect("failed to read --planes-file");
|
||
let planes: Vec<Plane> =
|
||
serde_json::from_str(&txt).expect("failed to parse --planes-file JSON");
|
||
data.planes = planes;
|
||
}
|
||
|
||
WorldIndex::build(data, precompute_neighbors)
|
||
}
|
||
|
||
fn now_epoch_ms() -> i64 {
|
||
SystemTime::now()
|
||
.duration_since(UNIX_EPOCH)
|
||
.unwrap()
|
||
.as_millis() as i64
|
||
}
|
||
|
||
fn main() {
|
||
let cli = Cli::parse();
|
||
|
||
match &cli.cmd {
|
||
Command::Board {
|
||
airport,
|
||
planes,
|
||
master,
|
||
salt,
|
||
day_salt,
|
||
at,
|
||
level,
|
||
json,
|
||
partition,
|
||
sort,
|
||
} => {
|
||
let world = load_world(&cli, false);
|
||
let (ap_idx, origin) = world
|
||
.get_airport(airport)
|
||
.unwrap_or_else(|| panic!("airport not found: {airport}"));
|
||
|
||
let plane_refs: Vec<&Plane> = planes
|
||
.split(',')
|
||
.map(|s| s.trim())
|
||
.filter(|s| !s.is_empty())
|
||
.map(|id| {
|
||
world
|
||
.planes
|
||
.get(id)
|
||
.unwrap_or_else(|| panic!("plane not found: {id}"))
|
||
})
|
||
.collect();
|
||
|
||
let epoch_ms = at.unwrap_or_else(now_epoch_ms);
|
||
let bucket = bucket_of(epoch_ms);
|
||
let s = salt.unwrap_or_else(|| board_salt(master, bucket));
|
||
let ds = day_salt.unwrap_or_else(|| shop_salt(master, day_of(epoch_ms)));
|
||
|
||
let opts = BoardOptions {
|
||
salt: s,
|
||
day_salt: ds,
|
||
level: *level,
|
||
..Default::default()
|
||
};
|
||
|
||
let mut scratch = BoardScratch::with_capacity();
|
||
let jobs = generate_board(&world, ap_idx, epoch_ms, &plane_refs, &opts, &mut scratch);
|
||
|
||
if *partition {
|
||
let sm = match sort {
|
||
CliSort::NetPerHour => SortMode::NetPerHour,
|
||
CliSort::GrossPay => SortMode::GrossPay,
|
||
CliSort::FlightTime => SortMode::FlightTime,
|
||
};
|
||
let part = partition_and_sort(
|
||
&world,
|
||
origin,
|
||
plane_refs[0],
|
||
jobs,
|
||
epoch_ms,
|
||
true,
|
||
sm,
|
||
&FilterMode::All,
|
||
);
|
||
if *json {
|
||
println!("{}", serde_json::to_string_pretty(&part).unwrap());
|
||
} else {
|
||
println!(
|
||
"Airport {} | bucket={} salt={} | ok={} off={} no={} | refresh in {}m",
|
||
origin.raw.code,
|
||
bucket,
|
||
s,
|
||
part.ok.len(),
|
||
part.off.len(),
|
||
part.no.len(),
|
||
part.refresh_mins
|
||
);
|
||
for r in &part.ok {
|
||
println!(
|
||
" {:7} {:6} -> {:6} {:6.1}nm pax={:<3} kg={:<5} pay=${:<7} net=${:<7} ${:<7.0}/hr {}",
|
||
r.job.kind.as_str(),
|
||
r.job.from,
|
||
r.job.to,
|
||
r.job.nm,
|
||
r.job.pax,
|
||
r.job.kg,
|
||
r.job.pay,
|
||
r.net_pay,
|
||
r.net_per_hour,
|
||
r.job.what.as_deref().unwrap_or("")
|
||
);
|
||
}
|
||
}
|
||
} else if *json {
|
||
println!("{}", serde_json::to_string_pretty(&jobs).unwrap());
|
||
} else {
|
||
println!(
|
||
"Airport {} | bucket={} salt={} | {} jobs",
|
||
origin.raw.code,
|
||
bucket,
|
||
s,
|
||
jobs.len()
|
||
);
|
||
for j in &jobs {
|
||
println!(
|
||
" {:7} {:6} -> {:6} {:6.1}nm pax={:<3} kg={:<5} pay=${:<7} {}",
|
||
j.kind.as_str(),
|
||
j.from,
|
||
j.to,
|
||
j.nm,
|
||
j.pax,
|
||
j.kg,
|
||
j.pay,
|
||
j.what.as_deref().unwrap_or("")
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
Command::Sim {
|
||
planes,
|
||
master,
|
||
salt,
|
||
at,
|
||
buckets,
|
||
level,
|
||
airports,
|
||
mode,
|
||
out,
|
||
json,
|
||
} => {
|
||
let t_idx = Instant::now();
|
||
let world = load_world(&cli, true);
|
||
let idx_secs = t_idx.elapsed().as_secs_f64();
|
||
|
||
let plane_refs: Vec<&Plane> = if let Some(list) = planes {
|
||
list.split(',')
|
||
.map(|s| s.trim())
|
||
.filter(|s| !s.is_empty())
|
||
.map(|id| {
|
||
world
|
||
.planes
|
||
.get(id)
|
||
.unwrap_or_else(|| panic!("plane not found: {id}"))
|
||
})
|
||
.collect()
|
||
} else {
|
||
world.plane_list.iter().collect()
|
||
};
|
||
|
||
let export_mode = match mode {
|
||
CliExportMode::Stats => ExportMode::StatsOnly,
|
||
CliExportMode::Csv => ExportMode::Csv,
|
||
CliExportMode::Ndjson => ExportMode::Ndjson,
|
||
};
|
||
|
||
let cfg = SimConfig {
|
||
master,
|
||
start_epoch_ms: *at,
|
||
num_buckets: *buckets,
|
||
explicit_salt: *salt,
|
||
level: *level,
|
||
aurora: false,
|
||
fair_weather: true,
|
||
airport_limit: *airports,
|
||
export_mode,
|
||
out_path: out.as_deref(),
|
||
};
|
||
|
||
let report = run_simulation(&world, &plane_refs, &cfg).expect("simulation failed");
|
||
|
||
if *json {
|
||
println!("{}", serde_json::to_string_pretty(&report).unwrap());
|
||
} else {
|
||
eprintln!(
|
||
"World indexed ({} airports, {} majors, {} pads, {} sights) in {:.3}s",
|
||
world.airports.len(),
|
||
world.majors.len(),
|
||
world.pads.len(),
|
||
world.sights.len(),
|
||
idx_secs
|
||
);
|
||
println!(
|
||
"Simulated {} boards ({} jobs) in {:.3}s [{:.0} boards/sec | {:.0} jobs/sec]",
|
||
report.total_boards,
|
||
report.total_jobs,
|
||
report.elapsed_secs,
|
||
report.boards_per_sec,
|
||
report.jobs_per_sec
|
||
);
|
||
println!(
|
||
"{:<18} {:>8} {:>9} {:>6} {:>9} {:>9} {:>9} {:>9} {:>7}",
|
||
"PLANE", "BOARDS", "JOBS", "J/B", "AVG $/HR", "BEST$/HR", "P50 $/HR", "P90 $/HR", "AVG NM"
|
||
);
|
||
for p in &report.planes {
|
||
println!(
|
||
"{:<18} {:>8} {:>9} {:>6.2} {:>9.0} {:>9.0} {:>9.0} {:>9.0} {:>7.1}",
|
||
p.plane_id,
|
||
p.boards,
|
||
p.jobs,
|
||
p.avg_jobs_per_board,
|
||
p.avg_net_per_hr,
|
||
p.avg_best_net_per_hr,
|
||
p.p50_net_per_hr,
|
||
p.p90_net_per_hr,
|
||
p.avg_nm
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|