cafeteria-sim 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,35 @@
1
+ """Discrete-event simulation and staffing optimization for cafeteria queues."""
2
+
3
+ from .config import DISTRIBUTIONS, PICKUP_MODES, SimulationConfig
4
+ from .metrics import max_overlap, percentile, wait_stats
5
+ from .optimization import OptimizationResult, StaffingCandidate, optimize_staffing
6
+ from .simulation import (
7
+ Customer,
8
+ ScenarioResult,
9
+ SimulationResult,
10
+ aggregate_results,
11
+ compare_windows,
12
+ run_replications,
13
+ run_simulation,
14
+ )
15
+
16
+ __all__ = [
17
+ "DISTRIBUTIONS",
18
+ "PICKUP_MODES",
19
+ "Customer",
20
+ "OptimizationResult",
21
+ "ScenarioResult",
22
+ "SimulationConfig",
23
+ "SimulationResult",
24
+ "StaffingCandidate",
25
+ "aggregate_results",
26
+ "compare_windows",
27
+ "max_overlap",
28
+ "optimize_staffing",
29
+ "percentile",
30
+ "run_replications",
31
+ "run_simulation",
32
+ "wait_stats",
33
+ ]
34
+
35
+ __version__ = "0.1.0"
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
cafeteria_sim/cli.py ADDED
@@ -0,0 +1,491 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from dataclasses import asdict
7
+
8
+ from .config import DISTRIBUTIONS, PICKUP_MODES, SimulationConfig
9
+ from .optimization import OptimizationResult, optimize_staffing
10
+ from .simulation import (
11
+ ScenarioResult,
12
+ SimulationResult,
13
+ aggregate_results,
14
+ compare_windows,
15
+ run_replications,
16
+ run_simulation,
17
+ )
18
+
19
+
20
+ def _add_common_options(parser: argparse.ArgumentParser) -> None:
21
+ parser.add_argument(
22
+ "--arrival-rate",
23
+ type=float,
24
+ default=120.0,
25
+ help="customer arrivals per hour (default: 120)",
26
+ )
27
+ parser.add_argument(
28
+ "--duration",
29
+ type=float,
30
+ default=120.0,
31
+ help="planning horizon in minutes (default: 120)",
32
+ )
33
+ parser.add_argument(
34
+ "--warmup",
35
+ type=float,
36
+ default=10.0,
37
+ help="warm-up minutes excluded from metrics (default: 10)",
38
+ )
39
+ parser.add_argument(
40
+ "--order-windows",
41
+ type=int,
42
+ default=3,
43
+ help="number of ordering windows (default: 3)",
44
+ )
45
+ parser.add_argument(
46
+ "--order-mean",
47
+ type=float,
48
+ default=75.0,
49
+ help="mean order service time in seconds (default: 75)",
50
+ )
51
+ parser.add_argument(
52
+ "--order-dist",
53
+ choices=DISTRIBUTIONS,
54
+ default="exponential",
55
+ help="order service-time distribution (default: exponential)",
56
+ )
57
+ parser.add_argument(
58
+ "--pickup-mode",
59
+ choices=PICKUP_MODES,
60
+ default="shared",
61
+ help="pickup layout: shared, per_window, or none (default: shared)",
62
+ )
63
+ parser.add_argument(
64
+ "--pickup-servers",
65
+ type=int,
66
+ default=2,
67
+ help="pickup servers for shared mode (default: 2)",
68
+ )
69
+ parser.add_argument(
70
+ "--pickup-mean",
71
+ type=float,
72
+ default=45.0,
73
+ help="mean pickup service time in seconds (default: 45)",
74
+ )
75
+ parser.add_argument(
76
+ "--pickup-dist",
77
+ choices=DISTRIBUTIONS,
78
+ default="exponential",
79
+ help="pickup service-time distribution (default: exponential)",
80
+ )
81
+ parser.add_argument(
82
+ "--max-order-queue",
83
+ type=int,
84
+ default=None,
85
+ help="balk when this many customers are already waiting to order",
86
+ )
87
+ parser.add_argument(
88
+ "--max-pickup-queue",
89
+ type=int,
90
+ default=None,
91
+ help="balk when this many customers are already waiting for pickup",
92
+ )
93
+ parser.add_argument(
94
+ "--order-patience",
95
+ type=float,
96
+ default=None,
97
+ help="mean order-queue patience in seconds (default: infinite)",
98
+ )
99
+ parser.add_argument(
100
+ "--pickup-patience",
101
+ type=float,
102
+ default=None,
103
+ help="mean pickup-queue patience in seconds (default: infinite)",
104
+ )
105
+ parser.add_argument(
106
+ "--seed",
107
+ type=int,
108
+ default=42,
109
+ help="random seed for the first replication (default: 42)",
110
+ )
111
+
112
+
113
+ def _build_config(args: argparse.Namespace) -> SimulationConfig:
114
+ return SimulationConfig(
115
+ arrival_rate_per_hour=args.arrival_rate,
116
+ duration_minutes=args.duration,
117
+ warmup_minutes=args.warmup,
118
+ order_windows=args.order_windows,
119
+ order_mean_s=args.order_mean,
120
+ order_dist=args.order_dist,
121
+ pickup_mode=args.pickup_mode,
122
+ pickup_servers=args.pickup_servers,
123
+ pickup_mean_s=args.pickup_mean,
124
+ pickup_dist=args.pickup_dist,
125
+ max_order_queue=args.max_order_queue,
126
+ max_pickup_queue=args.max_pickup_queue,
127
+ order_patience_mean_s=args.order_patience,
128
+ pickup_patience_mean_s=args.pickup_patience,
129
+ seed=args.seed,
130
+ )
131
+
132
+
133
+ def _run(config: SimulationConfig, replications: int) -> SimulationResult:
134
+ if replications == 1:
135
+ return run_simulation(config)
136
+ return aggregate_results(run_replications(config, replications))
137
+
138
+
139
+ def _format_seconds(value: float) -> str:
140
+ return f"{value:,.1f}"
141
+
142
+
143
+ def _print_summary(result: SimulationResult) -> None:
144
+ metrics = result.metrics
145
+ print(
146
+ f"觀察期間 : "
147
+ f"{result.config.duration_minutes - result.config.warmup_minutes:.0f} 分鐘 "
148
+ f"x {result.replications} 次模擬"
149
+ )
150
+ print(
151
+ f"到達/完成 : {metrics['arrivals']:.0f} / {metrics['served']:.0f} 人"
152
+ )
153
+ print(
154
+ f"放棄 : {metrics['abandoned']:.0f} 人 "
155
+ f"(點餐 balk {metrics['balked']:.0f} / renege {metrics['reneged_order']:.0f};"
156
+ f"取餐 balk {metrics['balked_pickup']:.0f} / renege {metrics['reneged_pickup']:.0f})"
157
+ )
158
+ print(
159
+ f"完成率/吞吐量 : {metrics['completion_rate'] * 100:.1f}% / "
160
+ f"{metrics['throughput_per_hour']:.1f} 人/小時"
161
+ )
162
+ print(
163
+ f"平均總等候 : {_format_seconds(metrics['total_wait_mean_s'])} 秒 "
164
+ f"(P95 {_format_seconds(metrics['total_wait_p95_s'])} 秒)"
165
+ )
166
+ print(
167
+ f" 點餐等候 : {_format_seconds(metrics['order_wait_mean_s'])} 秒 "
168
+ f"(P95 {_format_seconds(metrics['order_wait_p95_s'])} 秒)"
169
+ )
170
+ print(
171
+ f" 取餐等候 : {_format_seconds(metrics['pickup_wait_mean_s'])} 秒 "
172
+ f"(P95 {_format_seconds(metrics['pickup_wait_p95_s'])} 秒)"
173
+ )
174
+ print(
175
+ f"平均系統停留 : {_format_seconds(metrics['system_time_mean_s'])} 秒 "
176
+ f"(P95 {_format_seconds(metrics['system_time_p95_s'])} 秒)"
177
+ )
178
+ print(
179
+ f"使用率 : 點餐 {metrics['order_utilization'] * 100:.1f}% / "
180
+ f"取餐 {metrics['pickup_utilization'] * 100:.1f}%"
181
+ )
182
+ print(
183
+ f"平均排隊人數 : 點餐 {metrics['avg_order_queue']:.2f} 人 / "
184
+ f"取餐 {metrics['avg_pickup_queue']:.2f} 人"
185
+ )
186
+ print(
187
+ f"最大排隊人數 : 點餐 {metrics['max_order_queue']:.0f} 人 / "
188
+ f"取餐 {metrics['max_pickup_queue']:.0f} 人"
189
+ )
190
+
191
+
192
+ def _print_comparison(scenarios: list[ScenarioResult]) -> None:
193
+ header = (
194
+ f"{'Win':>4} {'Mean(s)':>10} {'P95(s)':>10} "
195
+ f"{'Done%':>8} {'PerHour':>9} {'Order%':>9} {'Pickup%':>9} {'MaxQ':>6}"
196
+ )
197
+ print(header)
198
+ print("-" * len(header))
199
+ for scenario in scenarios:
200
+ metrics = scenario.metrics
201
+ print(
202
+ f"{scenario.config.order_windows:>4} "
203
+ f"{_format_seconds(metrics['total_wait_mean_s']):>10} "
204
+ f"{_format_seconds(metrics['total_wait_p95_s']):>10} "
205
+ f"{metrics['completion_rate'] * 100:>7.1f}% "
206
+ f"{metrics['throughput_per_hour']:>9.1f} "
207
+ f"{metrics['order_utilization'] * 100:>8.1f}% "
208
+ f"{metrics['pickup_utilization'] * 100:>8.1f}% "
209
+ f"{metrics['max_order_queue']:>9.0f}"
210
+ )
211
+
212
+
213
+ def _print_optimization(result: OptimizationResult) -> None:
214
+ targets = []
215
+ if result.target_mean_wait_s is not None:
216
+ targets.append(f"平均總等候 <= {result.target_mean_wait_s:.0f} 秒")
217
+ if result.target_p95_wait_s is not None:
218
+ targets.append(f"P95 總等候 <= {result.target_p95_wait_s:.0f} 秒")
219
+ print("目標:" + "、".join(targets))
220
+ print(f"模擬次數:每次配置 {result.replications} 次,取顧客等候時間池化後計算")
221
+ print()
222
+
223
+ best = result.best
224
+ if best is None:
225
+ print("找不到符合目標的人力配置;請放寬目標或提高上限。")
226
+ print()
227
+ print("等候時間最短的候選方案:")
228
+ for candidate in sorted(
229
+ result.candidates, key=lambda item: item.metrics["total_wait_mean_s"]
230
+ )[:3]:
231
+ print(
232
+ f" 窗數 {candidate.order_windows}、取餐檯 {candidate.pickup_servers}:"
233
+ f"平均 {_format_seconds(candidate.metrics['total_wait_mean_s'])} 秒、"
234
+ f"P95 {_format_seconds(candidate.metrics['total_wait_p95_s'])} 秒、"
235
+ f"成本 {candidate.hourly_cost:,.0f} 元/小時"
236
+ )
237
+ return
238
+
239
+ print(
240
+ f"最佳方案:點餐窗口 {best.order_windows} 個、取餐檯 {best.pickup_servers} 個,"
241
+ f"成本 {best.hourly_cost:,.0f} 元/小時"
242
+ )
243
+ print(
244
+ f" 平均總等候 {_format_seconds(best.metrics['total_wait_mean_s'])} 秒、"
245
+ f"P95 {_format_seconds(best.metrics['total_wait_p95_s'])} 秒、"
246
+ f"完成率 {best.metrics['completion_rate'] * 100:.1f}%"
247
+ )
248
+ print()
249
+ print("可行候選方案(依成本排序):")
250
+ header = (
251
+ f"{'Win':>4} {'Pickup':>7} {'Cost/h':>10} "
252
+ f"{'Mean(s)':>10} {'P95(s)':>10} {'Done%':>8}"
253
+ )
254
+ print(header)
255
+ print("-" * len(header))
256
+ for candidate in result.ranked()[:8]:
257
+ print(
258
+ f"{candidate.order_windows:>4} {candidate.pickup_servers:>6} "
259
+ f"{candidate.hourly_cost:>10,.0f} "
260
+ f"{_format_seconds(candidate.metrics['total_wait_mean_s']):>10} "
261
+ f"{_format_seconds(candidate.metrics['total_wait_p95_s']):>10} "
262
+ f"{candidate.metrics['completion_rate'] * 100:>7.1f}%"
263
+ )
264
+
265
+
266
+ def _cmd_run(args: argparse.Namespace) -> int:
267
+ config = _build_config(args)
268
+ result = _run(config, args.replications)
269
+ if args.json:
270
+ payload = {
271
+ "config": asdict(config),
272
+ "replications": result.replications,
273
+ "metrics": result.metrics,
274
+ }
275
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
276
+ else:
277
+ print("== 學餐排隊模擬 ==")
278
+ _print_summary(result)
279
+ return 0
280
+
281
+
282
+ def _window_list(value: str) -> list[int]:
283
+ try:
284
+ counts = [int(part.strip()) for part in value.split(",") if part.strip()]
285
+ except ValueError as exc:
286
+ raise argparse.ArgumentTypeError(
287
+ "use comma-separated integers, for example 1,2,3,4"
288
+ ) from exc
289
+ if not counts or any(count < 1 for count in counts):
290
+ raise argparse.ArgumentTypeError("window counts must be integers >= 1")
291
+ return counts
292
+
293
+
294
+ def _cmd_compare(args: argparse.Namespace) -> int:
295
+ config = _build_config(args)
296
+ scenarios = compare_windows(config, args.windows, args.replications)
297
+ if args.json:
298
+ payload = {
299
+ "config": asdict(config),
300
+ "replications": args.replications,
301
+ "scenarios": [scenario.to_dict() for scenario in scenarios],
302
+ }
303
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
304
+ else:
305
+ print("== 加開點餐窗口的情境比較 ==")
306
+ print(
307
+ f"到達率 {config.arrival_rate_per_hour:.0f} 人/小時、"
308
+ f"取餐模式 {config.pickup_mode}、取餐檯 {config.pickup_servers} 個、"
309
+ f"每次情境 {args.replications} 次模擬"
310
+ )
311
+ print()
312
+ _print_comparison(scenarios)
313
+ return 0
314
+
315
+
316
+ def _cmd_optimize(args: argparse.Namespace) -> int:
317
+ if args.target_mean_wait is None and args.target_p95_wait is None:
318
+ args.target_mean_wait = 180.0
319
+ config = _build_config(args)
320
+ result = optimize_staffing(
321
+ config,
322
+ max_order_windows=args.max_order_windows,
323
+ max_pickup_servers=args.max_pickup_servers,
324
+ order_window_cost=args.order_cost,
325
+ pickup_server_cost=args.pickup_cost,
326
+ target_mean_wait_s=args.target_mean_wait,
327
+ target_p95_wait_s=args.target_p95_wait,
328
+ replications=args.replications,
329
+ )
330
+ if args.json:
331
+ print(json.dumps(result.to_dict(), ensure_ascii=False, indent=2))
332
+ else:
333
+ print("== 最低成本人力配置 ==")
334
+ _print_optimization(result)
335
+ return 0 if result.best is not None else 1
336
+
337
+
338
+ def _cmd_demo(args: argparse.Namespace) -> int:
339
+ base = SimulationConfig(
340
+ arrival_rate_per_hour=120.0,
341
+ duration_minutes=120.0,
342
+ warmup_minutes=10.0,
343
+ order_windows=3,
344
+ order_mean_s=75.0,
345
+ order_dist="exponential",
346
+ pickup_mode="shared",
347
+ pickup_servers=2,
348
+ pickup_mean_s=45.0,
349
+ pickup_dist="exponential",
350
+ seed=7,
351
+ )
352
+ scenarios = compare_windows(base, [1, 2, 3, 4, 5], replications=3)
353
+ result = optimize_staffing(
354
+ base,
355
+ max_order_windows=6,
356
+ max_pickup_servers=4,
357
+ order_window_cost=150.0,
358
+ pickup_server_cost=100.0,
359
+ target_mean_wait_s=180.0,
360
+ target_p95_wait_s=450.0,
361
+ replications=3,
362
+ )
363
+
364
+ print("== cafeteria-sim 示範:午餐尖峰 ==")
365
+ print(
366
+ "情境:每小時 120 人到達;點餐平均 75 秒;共用取餐區、"
367
+ "每個取餐檯平均 45 秒;模擬 2 小時,前 10 分鐘暖機。"
368
+ )
369
+ print()
370
+ print("1) 只加開點餐窗口,取餐人力固定 2 人")
371
+ _print_comparison(scenarios)
372
+ print()
373
+ print("2) 以平均等候 <= 180 秒、P95 <= 450 秒為目標,尋找最低成本配置")
374
+ print(" 成本假設:點餐窗口 150 元/小時、取餐檯 100 元/小時")
375
+ print()
376
+ _print_optimization(result)
377
+ print()
378
+ print("完成:套件已可執行模擬、情境比較與人力最佳化。")
379
+ return 0
380
+
381
+
382
+ def build_parser() -> argparse.ArgumentParser:
383
+ parser = argparse.ArgumentParser(
384
+ prog="cafeteria-sim",
385
+ description=(
386
+ "Discrete-event simulation and staffing optimization for "
387
+ "school cafeteria queues."
388
+ ),
389
+ )
390
+ subparsers = parser.add_subparsers(dest="command", required=True)
391
+
392
+ run_parser = subparsers.add_parser("run", help="run one scenario")
393
+ _add_common_options(run_parser)
394
+ run_parser.add_argument(
395
+ "--replications",
396
+ type=int,
397
+ default=1,
398
+ help="number of independent replications (default: 1)",
399
+ )
400
+ run_parser.add_argument("--json", action="store_true", help="print JSON")
401
+ run_parser.set_defaults(func=_cmd_run)
402
+
403
+ compare_parser = subparsers.add_parser(
404
+ "compare", help="compare different numbers of ordering windows"
405
+ )
406
+ _add_common_options(compare_parser)
407
+ compare_parser.add_argument(
408
+ "--windows",
409
+ type=_window_list,
410
+ default=[1, 2, 3, 4, 5],
411
+ help="comma-separated window counts to compare (default: 1,2,3,4,5)",
412
+ )
413
+ compare_parser.add_argument(
414
+ "--replications",
415
+ type=int,
416
+ default=3,
417
+ help="number of independent replications per scenario (default: 3)",
418
+ )
419
+ compare_parser.add_argument("--json", action="store_true", help="print JSON")
420
+ compare_parser.set_defaults(func=_cmd_compare)
421
+
422
+ optimize_parser = subparsers.add_parser(
423
+ "optimize", help="find the cheapest staffing plan that meets a wait target"
424
+ )
425
+ _add_common_options(optimize_parser)
426
+ optimize_parser.add_argument(
427
+ "--target-mean-wait",
428
+ type=float,
429
+ default=None,
430
+ help="maximum mean total waiting time in seconds (default: 180)",
431
+ )
432
+ optimize_parser.add_argument(
433
+ "--target-p95-wait",
434
+ type=float,
435
+ default=None,
436
+ help="maximum p95 total waiting time in seconds",
437
+ )
438
+ optimize_parser.add_argument(
439
+ "--max-order-windows",
440
+ type=int,
441
+ default=6,
442
+ help="largest number of ordering windows to consider (default: 6)",
443
+ )
444
+ optimize_parser.add_argument(
445
+ "--max-pickup-servers",
446
+ type=int,
447
+ default=4,
448
+ help="largest number of pickup servers to consider (default: 4)",
449
+ )
450
+ optimize_parser.add_argument(
451
+ "--order-cost",
452
+ type=float,
453
+ default=150.0,
454
+ help="hourly cost of one ordering window (default: 150)",
455
+ )
456
+ optimize_parser.add_argument(
457
+ "--pickup-cost",
458
+ type=float,
459
+ default=100.0,
460
+ help="hourly cost of one pickup server (default: 100)",
461
+ )
462
+ optimize_parser.add_argument(
463
+ "--replications",
464
+ type=int,
465
+ default=3,
466
+ help="number of independent replications per plan (default: 3)",
467
+ )
468
+ optimize_parser.add_argument("--json", action="store_true", help="print JSON")
469
+ optimize_parser.set_defaults(func=_cmd_optimize)
470
+
471
+ demo_parser = subparsers.add_parser(
472
+ "demo", help="run the built-in lunch-peak demonstration"
473
+ )
474
+ demo_parser.set_defaults(func=_cmd_demo)
475
+
476
+ return parser
477
+
478
+
479
+ def main(argv: list[str] | None = None) -> int:
480
+ if hasattr(sys.stdout, "reconfigure"):
481
+ try:
482
+ sys.stdout.reconfigure(encoding="utf-8")
483
+ except (OSError, ValueError):
484
+ pass
485
+ parser = build_parser()
486
+ args = parser.parse_args(argv)
487
+ try:
488
+ return int(args.func(args))
489
+ except ValueError as exc:
490
+ print(f"error: {exc}", file=sys.stderr)
491
+ return 2
@@ -0,0 +1,91 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+ DISTRIBUTIONS = ("exponential", "deterministic", "uniform", "triangular")
6
+ PICKUP_MODES = ("shared", "per_window", "none")
7
+
8
+
9
+ @dataclass(frozen=True, slots=True)
10
+ class SimulationConfig:
11
+ """Configuration for one cafeteria simulation run.
12
+
13
+ Rates and durations are explicit about their units: arrival rates are
14
+ customers per hour, service means are seconds, and the planning horizon is
15
+ minutes. The observation window is [warmup, duration]; customers who arrive
16
+ before the warm-up are simulated but excluded from reported statistics.
17
+ """
18
+
19
+ arrival_rate_per_hour: float = 120.0
20
+ duration_minutes: float = 120.0
21
+ warmup_minutes: float = 10.0
22
+
23
+ order_windows: int = 3
24
+ order_mean_s: float = 75.0
25
+ order_dist: str = "exponential"
26
+
27
+ pickup_mode: str = "shared"
28
+ pickup_servers: int = 2
29
+ pickup_mean_s: float = 45.0
30
+ pickup_dist: str = "exponential"
31
+
32
+ max_order_queue: int | None = None
33
+ max_pickup_queue: int | None = None
34
+ order_patience_mean_s: float | None = None
35
+ pickup_patience_mean_s: float | None = None
36
+
37
+ seed: int = 42
38
+
39
+ def __post_init__(self) -> None:
40
+ if self.arrival_rate_per_hour <= 0:
41
+ raise ValueError("arrival_rate_per_hour must be positive")
42
+ if self.duration_minutes <= 0:
43
+ raise ValueError("duration_minutes must be positive")
44
+ if self.warmup_minutes < 0:
45
+ raise ValueError("warmup_minutes must be non-negative")
46
+ if self.warmup_minutes >= self.duration_minutes:
47
+ raise ValueError("warmup_minutes must be shorter than duration_minutes")
48
+ if not isinstance(self.order_windows, int) or self.order_windows < 1:
49
+ raise ValueError("order_windows must be an integer >= 1")
50
+ if not isinstance(self.pickup_servers, int) or self.pickup_servers < 1:
51
+ raise ValueError("pickup_servers must be an integer >= 1")
52
+ if self.order_mean_s <= 0:
53
+ raise ValueError("order_mean_s must be positive")
54
+ if self.pickup_mean_s <= 0:
55
+ raise ValueError("pickup_mean_s must be positive")
56
+ if self.order_dist not in DISTRIBUTIONS:
57
+ raise ValueError(f"order_dist must be one of {DISTRIBUTIONS}")
58
+ if self.pickup_dist not in DISTRIBUTIONS:
59
+ raise ValueError(f"pickup_dist must be one of {DISTRIBUTIONS}")
60
+ if self.pickup_mode not in PICKUP_MODES:
61
+ raise ValueError(f"pickup_mode must be one of {PICKUP_MODES}")
62
+ if self.max_order_queue is not None and (
63
+ not isinstance(self.max_order_queue, int) or self.max_order_queue < 0
64
+ ):
65
+ raise ValueError("max_order_queue must be None or an integer >= 0")
66
+ if self.max_pickup_queue is not None and (
67
+ not isinstance(self.max_pickup_queue, int) or self.max_pickup_queue < 0
68
+ ):
69
+ raise ValueError("max_pickup_queue must be None or an integer >= 0")
70
+ if self.order_patience_mean_s is not None and self.order_patience_mean_s <= 0:
71
+ raise ValueError("order_patience_mean_s must be None or positive")
72
+ if self.pickup_patience_mean_s is not None and self.pickup_patience_mean_s <= 0:
73
+ raise ValueError("pickup_patience_mean_s must be None or positive")
74
+ if not isinstance(self.seed, int) or self.seed < 0:
75
+ raise ValueError("seed must be a non-negative integer")
76
+
77
+ @property
78
+ def duration_s(self) -> float:
79
+ return self.duration_minutes * 60.0
80
+
81
+ @property
82
+ def warmup_s(self) -> float:
83
+ return self.warmup_minutes * 60.0
84
+
85
+ @property
86
+ def effective_duration_s(self) -> float:
87
+ return self.duration_s - self.warmup_s
88
+
89
+ @property
90
+ def effective_duration_hours(self) -> float:
91
+ return self.effective_duration_s / 3600.0
@@ -0,0 +1,28 @@
1
+ from __future__ import annotations
2
+
3
+ import random
4
+ from collections.abc import Callable
5
+
6
+ Sampler = Callable[[], float]
7
+
8
+
9
+ def make_sampler(name: str, mean: float, rng: random.Random) -> Sampler:
10
+ """Return a positive service-time sampler with the requested mean."""
11
+
12
+ if mean <= 0:
13
+ raise ValueError("mean must be positive")
14
+
15
+ if name == "exponential":
16
+ rate = 1.0 / mean
17
+ return lambda: rng.expovariate(rate)
18
+
19
+ if name == "deterministic":
20
+ return lambda: mean
21
+
22
+ if name == "uniform":
23
+ return lambda: rng.uniform(0.5 * mean, 1.5 * mean)
24
+
25
+ if name == "triangular":
26
+ return lambda: rng.triangular(0.5 * mean, mean, 1.5 * mean)
27
+
28
+ raise ValueError(f"unknown distribution: {name}")