-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2406 lines (1949 loc) · 78.3 KB
/
app.py
File metadata and controls
2406 lines (1949 loc) · 78.3 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import os
import sys
import asyncio
import random
from datetime import datetime
from typing import Literal, Optional, List, Dict, Tuple
from threading import Lock
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from pathlib import Path
from sqlalchemy import (
create_engine,
Column,
String,
Float,
Boolean,
Integer,
ForeignKey,
Index,
func,
case
)
from sqlalchemy.orm import sessionmaker, declarative_base, relationship
import json
from typing import Any
from dataclasses import dataclass, field
import contextlib
from collections import defaultdict
# ---------------------------------
# DB setup & sim time
# ---------------------------------
RESUME_DB = ("--resume" in sys.argv) or (os.getenv("BOXES_RESUME", "0") == "1")
DB_PATH = "boxes.db"
LOG_DIR = Path(os.getenv("BOXES_LOG_DIR", "logs"))
LOG_DIR.mkdir(parents=True, exist_ok=True)
FINAL_LIVE_PRINTED: bool = False
# If not resuming, delete any existing DB file so we start fresh
if not RESUME_DB and os.path.exists(DB_PATH):
os.remove(DB_PATH)
engine = create_engine("sqlite:///boxes.db", future=True)
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
Base = declarative_base()
SERVER_START = datetime.utcnow()
TIME_LIMIT_SEC = 600
# --- time freeze / scoring state ---
_TIME_LOCK = Lock()
FROZEN_TIME: Optional[float] = None # sim-time value once time is up (typically TIME_LIMIT_SEC)
TIME_UP: bool = False
FINAL_SCORE: Optional[dict] = None # computed once at time-up
# Optional: control any manual prints in endpoints
ENABLE_STATE_PRINTS = False
# --- dynamic end condition: last box deadline (sim-time) ---
FINAL_DEADLINE_SIM: Optional[float] = None
# --- watchdog task to guarantee final print even if no requests come in ---
_FINALIZE_WATCHDOG_TASK: Optional[asyncio.Task] = None
# ---------------------------------
# Agent detection parameters
# ---------------------------------
# Each agent has per-property probabilities:
# present: P(detect=True | property actually present)
# absent: P(detect=True | property actually absent) (false-positive rate)
# Fallback for unknown agents (if any)
DEFAULT_AGENT_PARAMS = {
"X": {"present": 0.75, "absent": 0.25},
"Y": {"present": 0.75, "absent": 0.25},
}
# ---------------------------------
# Hardcoded scenario
# ---------------------------------
USE_HARDCODED_SCENARIO = True
SCENARIO_ID = "hard_10_v1"
# deadlines are offsets from scenario start time (seconds)
# has_X/has_Y define the ground truth
# times are durations (seconds)
# ---------------------------------
# 2) Add release_time to SCENARIO_BOXES
# (only adding the field; you can tune values later)
# ---------------------------------
SCENARIO_BOXES = {
1: {"release_time": 0, "has_X": True, "has_Y": False, "deadline_offset": 140,
"sense_X": 18, "sense_Y": 18, "disp_X": 220, "disp_Y": 220,
"senseable": ["X"]},
2: {"release_time": 0, "has_X": False, "has_Y": True, "deadline_offset": 190,
"sense_X": 18, "sense_Y": 18, "disp_X": 220, "disp_Y": 220,
"senseable": ["Y"]},
3: {"release_time": 25, "has_X": False, "has_Y": False, "deadline_offset": 175,
"sense_X": 15, "sense_Y": 15, "disp_X": 120, "disp_Y": 120,
"senseable": ["X"]},
4: {"release_time": 35, "has_X": False, "has_Y": False, "deadline_offset": 180,
"sense_X": 15, "sense_Y": 15, "disp_X": 120, "disp_Y": 120,
"senseable": ["Y"]},
5: {"release_time": 140, "has_X": False, "has_Y": True, "deadline_offset": 260,
"sense_X": 20, "sense_Y": 22, "disp_X": 240, "disp_Y": 240,
"senseable": ["Y"]},
6: {"release_time": 140, "has_X": True, "has_Y": False, "deadline_offset": 300,
"sense_X": 22, "sense_Y": 20, "disp_X": 240, "disp_Y": 240,
"senseable": ["X"]},
7: {"release_time": 140, "has_X": False, "has_Y": False, "deadline_offset": 275,
"sense_X": 18, "sense_Y": 18, "disp_X": 90, "disp_Y": 90,
"senseable": ["X", "Y"]},
# --- DILEMMA BOX: needs BOTH X and Y, tight deadline ---
8: {"release_time": 165, "has_X": True, "has_Y": True, "deadline_offset": 215,
"sense_X": 12, "sense_Y": 12, "disp_X": 160, "disp_Y": 160,
"senseable": ["X", "Y"]},
9: {"release_time": 300, "has_X": True, "has_Y": False, "deadline_offset": 430,
"sense_X": 20, "sense_Y": 20, "disp_X": 260, "disp_Y": 260,
"senseable": ["X"]},
10: {"release_time": 340, "has_X": False, "has_Y": True, "deadline_offset": 470,
"sense_X": 20, "sense_Y": 20, "disp_X": 260, "disp_Y": 260,
"senseable": ["Y"]},
}
AGENT_DETECTION_PARAMS = {
"robot": {
"X": {"present": 0.92, "absent": 0.06}, # very reliable
"Y": {"present": 0.92, "absent": 0.06},
},
"human_a": { # can sense only X
"X": {"present": 0.82, "absent": 0.18}, # okay but noisier than robot
"Y": {"present": 0.00, "absent": 1.00}, # unused / impossible
},
"human_b": { # can sense only Y
"X": {"present": 0.00, "absent": 1.00}, # unused / impossible
"Y": {"present": 0.82, "absent": 0.18},
},
}
objects_pre_data = {
1: {"x": 3.0, "y": -1.0},
2: {"x": 0.0, "y": -1.0},
3: {"x": 1.0, "y": 1.0},
4: {"x": -1.0, "y": 2.0},
5: {"x": 3.0, "y": 1.0},
6: {"x": 4.0, "y": 0.5},
7: {"x": 2.0, "y": -1.0},
8: {"x": 3.0, "y": -3.0},
9: {"x": 4.0, "y": -5.0},
10: {"x": 6.0, "y": -4.5},
}
def sim_time() -> float:
global FROZEN_TIME, TIME_UP, FINAL_DEADLINE_SIM
elapsed = (datetime.utcnow() - SERVER_START).total_seconds()
# freeze at last box deadline if known; else fallback
limit = float(FINAL_DEADLINE_SIM) if FINAL_DEADLINE_SIM is not None else float(TIME_LIMIT_SEC)
should_finalize = False
with _TIME_LOCK:
if FROZEN_TIME is not None:
return float(FROZEN_TIME)
if elapsed >= limit:
FROZEN_TIME = float(limit)
TIME_UP = True
should_finalize = True
if should_finalize:
maybe_finalize_time_and_score()
return float(elapsed)
def compute_live_score(db) -> dict:
"""
Live scoreboard (not just final):
- senses completed per agent
- sensing accuracy per agent (detected == ground truth)
- disposals completed per agent
- disposal correctness per agent:
* correct_on_time (== success True in your logic)
* wrong_property (disposed when property not present, even if on time)
* late (completed after deadline, regardless of property)
- totals
"""
# --------
# Sensing
# --------
# Accuracy: compare SenseResult.detected to Box.has_X/has_Y
sensed_rows = (
db.query(
SenseResult.agent_id.label("agent"),
func.count().label("sensed_completed"),
func.sum(
case(
# correct if detected == ground truth presence
(
case(
(SenseResult.property == "X", Box.has_X),
else_=Box.has_Y,
) == SenseResult.detected,
1,
),
else_=0,
)
).label("sensed_correct"),
)
.join(Box, Box.id == SenseResult.box_id)
.filter(SenseResult.status == "completed")
.group_by(SenseResult.agent_id)
.all()
)
sense_by_agent = {}
for r in sensed_rows:
total = int(r.sensed_completed or 0)
correct = int(r.sensed_correct or 0)
sense_by_agent[str(r.agent)] = {
"completed": total,
"correct": correct,
"accuracy": (correct / total) if total > 0 else None,
}
# ---------
# Disposal (RAW + CREDITED)
# ---------
# RAW: counts every completed disposal record (your current behavior)
disp_by_agent_raw: Dict[str, Dict[str, int]] = {}
completed_disposals = (
db.query(DisposalResult, Box)
.join(Box, Box.id == DisposalResult.box_id)
.filter(DisposalResult.status == "completed")
.all()
)
for dr, box in completed_disposals:
a = str(dr.agent_id)
disp_by_agent_raw.setdefault(a, {
"completed": 0,
"correct_on_time": 0,
"wrong_property": 0,
"late": 0,
})
disp_by_agent_raw[a]["completed"] += 1
prop = str(dr.property)
prop_present = bool(box.has_X) if prop == "X" else bool(box.has_Y)
late = (dr.completed_at is not None) and (float(dr.completed_at) > float(box.deadline))
if late:
disp_by_agent_raw[a]["late"] += 1
if not prop_present:
disp_by_agent_raw[a]["wrong_property"] += 1
if dr.success is True:
disp_by_agent_raw[a]["correct_on_time"] += 1
# CREDITED: dedup scoring so each (box_id,prop) can only earn points once.
# Rule: if multiple on-time successes exist, earliest completed_at gets the credit.
disp_by_agent_credited: Dict[str, Dict[str, int]] = {}
credited_pairs: set[tuple[int, str]] = set()
# Consider only disposals that claim success, and verify on-time with box.deadline.
success_candidates = [
(dr, box) for (dr, box) in completed_disposals
if dr.success is True and dr.completed_at is not None
and float(dr.completed_at) <= float(box.deadline)
]
success_candidates.sort(key=lambda pair: float(pair[0].completed_at)) # earliest wins
for dr, box in success_candidates:
key = (int(dr.box_id), str(dr.property))
if key in credited_pairs:
continue
credited_pairs.add(key)
a = str(dr.agent_id)
disp_by_agent_credited.setdefault(a, {"credited_success_on_time": 0})
disp_by_agent_credited[a]["credited_success_on_time"] += 1
# Totals
total_disposed_raw = sum(v["completed"] for v in disp_by_agent_raw.values())
total_correct_raw = sum(v["correct_on_time"] for v in disp_by_agent_raw.values())
total_correct_credited = len(credited_pairs)
# -----------------------
# NEW: per-agent itemized lists
# -----------------------
sensed_items_by_agent: Dict[str, List[Dict[str, Any]]] = {}
sensed_items = (
db.query(SenseResult, Box)
.join(Box, Box.id == SenseResult.box_id)
.filter(SenseResult.status == "completed")
.order_by(SenseResult.completed_at.asc())
.all()
)
for sr, box in sensed_items:
a = str(sr.agent_id)
sensed_items_by_agent.setdefault(a, []).append({
"box_id": int(sr.box_id),
"prop": str(sr.property),
"detected": bool(sr.detected) if sr.detected is not None else None,
"probability": float(sr.probability) if sr.probability is not None else None,
"completed_at": float(sr.completed_at) if sr.completed_at is not None else None,
# optional: include ground truth so you can inspect correctness quickly
"truth_present": bool(box.has_X) if str(sr.property) == "X" else bool(box.has_Y),
})
disposed_items_by_agent: Dict[str, List[Dict[str, Any]]] = {}
disposed_items = (
db.query(DisposalResult, Box)
.join(Box, Box.id == DisposalResult.box_id)
.filter(DisposalResult.status == "completed")
.order_by(DisposalResult.completed_at.asc())
.all()
)
for dr, box in disposed_items:
a = str(dr.agent_id)
prop = str(dr.property)
prop_present = bool(box.has_X) if prop == "X" else bool(box.has_Y)
late = (dr.completed_at is not None) and (dr.completed_at > box.deadline)
wrong_property = (not prop_present)
disposed_items_by_agent.setdefault(a, []).append({
"box_id": int(dr.box_id),
"prop": prop,
"success": bool(dr.success) if dr.success is not None else None,
"completed_at": float(dr.completed_at) if dr.completed_at is not None else None,
"late": bool(late),
"wrong_property": bool(wrong_property),
"deadline": float(box.deadline),
# optional: include truth
"truth_present": bool(prop_present),
})
# Totals (use the ones we already computed)
total_sensed = sum(v["completed"] for v in sense_by_agent.values())
# -----------------------
# NEW: per-box max disposal attempt duration (any prop, any outcome)
# Helpers now overlap across properties (same box_id).
# -----------------------
per_box_max_dispose_attempt: Dict[int, Dict[str, Any]] = {}
attempts_by_box: Dict[int, List[Dict[str, Any]]] = defaultdict(list)
disp_attempts = (
db.query(DisposalResult, Box)
.join(Box, Box.id == DisposalResult.box_id)
.filter(DisposalResult.status.in_(["completed", "cancelled"]))
.all()
)
for dr, box in disp_attempts:
box_id = int(dr.box_id)
prop = str(dr.property)
start_t = dr.started_at if dr.started_at is not None else dr.requested_at
end_t = dr.completed_at if dr.status == "completed" else dr.cancelled_at
if start_t is None or end_t is None:
continue
dur = float(end_t) - float(start_t)
if dur < 0:
continue
# store interval for helper computation (per-box, cross-prop)
attempts_by_box[box_id].append({
"agent_id": str(dr.agent_id),
"prop": prop,
"start": float(start_t),
"end": float(end_t),
"status": str(dr.status),
"success": bool(dr.success) if dr.success is not None else None,
})
# compute useful flags (for the "max attempt" record)
prop_present = bool(box.has_X) if prop == "X" else bool(box.has_Y)
late = (dr.completed_at is not None) and (float(dr.completed_at) > float(box.deadline))
wrong_property = (not prop_present)
prev = per_box_max_dispose_attempt.get(box_id)
if (prev is None) or (dur > float(prev["max_duration_sec"])):
per_box_max_dispose_attempt[box_id] = {
"max_duration_sec": float(dur),
"agent_id": str(dr.agent_id),
"prop": prop,
"status": str(dr.status), # completed/cancelled
"success": bool(dr.success) if dr.success is not None else None,
"started_at": float(start_t),
"ended_at": float(end_t),
"deadline": float(box.deadline),
"late": bool(late),
"wrong_property": bool(wrong_property),
"truth_present": bool(prop_present),
# NEW:
# helpers: list of agents that overlapped this max-attempt window,
# regardless of their requested property.
"helpers": [],
# optional richer view:
"helpers_detailed": [],
}
def overlaps(a_start: float, a_end: float, b_start: float, b_end: float) -> bool:
return max(a_start, b_start) <= min(a_end, b_end)
for box_id, info in per_box_max_dispose_attempt.items():
a_start = float(info["started_at"])
a_end = float(info["ended_at"])
helpers = {} # agent_id -> set(props)
for rec in attempts_by_box.get(int(box_id), []):
if overlaps(a_start, a_end, float(rec["start"]), float(rec["end"])):
helpers.setdefault(str(rec["agent_id"]), set()).add(str(rec["prop"]))
# If you want helpers-only, uncomment next line:
# helpers.pop(str(info["agent_id"]), None)
info["helpers"] = sorted(helpers.keys())
info["helpers_detailed"] = [
{"agent_id": aid, "props": sorted(list(props))}
for aid, props in sorted(helpers.items(), key=lambda kv: kv[0])
]
# -----------------------
# NEW: current agent activity
# -----------------------
agents_activity: Dict[str, Dict[str, Any]] = {}
# Running senses
running_senses = (
db.query(SenseResult, Box)
.join(Box, Box.id == SenseResult.box_id)
.filter(SenseResult.status == "running")
.all()
)
for sr, box in running_senses:
a = str(sr.agent_id)
agents_activity[a] = {
"type": "sense",
"box_id": int(sr.box_id),
"prop": str(sr.property),
"started_at": float(sr.started_at) if sr.started_at is not None else None,
"elapsed_sec": (
sim_time() - float(sr.started_at)
if sr.started_at is not None
else None
),
"deadline": float(box.deadline),
}
running_disposals = (
db.query(DisposalResult, Box)
.join(Box, Box.id == DisposalResult.box_id)
.filter(DisposalResult.status == "running")
.all()
)
for dr, box in running_disposals:
a = str(dr.agent_id)
agents_activity[a] = {
"type": "dispose",
"box_id": int(dr.box_id),
"prop": str(dr.property),
"started_at": float(dr.started_at) if dr.started_at is not None else None,
"elapsed_sec": (
sim_time() - float(dr.started_at)
if dr.started_at is not None
else None
),
"deadline": float(box.deadline),
}
# Known agents = anyone who has ever acted
known_agents = set(sense_by_agent.keys()) | set(disp_by_agent_raw.keys())
for a in known_agents:
agents_activity.setdefault(a, {
"type": "idle"
})
return {
"t": sim_time(),
"time_up": bool(TIME_UP),
"sense_by_agent": sense_by_agent,
# Use RAW as the main scoreboard (matches 'completed/correct_on_time/wrong_property/late')
"dispose_by_agent": disp_by_agent_raw,
# Optional: keep credited view separately
"dispose_by_agent_credited": disp_by_agent_credited,
"sensed_items_by_agent": sensed_items_by_agent,
"disposed_items_by_agent": disposed_items_by_agent,
"agents_activity": agents_activity,
"totals": {
"sensed_completed": total_sensed,
"disposed_completed": total_disposed_raw,
"correct_disposals_on_time_raw": total_correct_raw,
"correct_disposals_on_time_credited": total_correct_credited,
"per_box_max_dispose_attempt": per_box_max_dispose_attempt,
},
}
def print_live_score(db, reason: str = "") -> None:
score = compute_live_score(db)
tag = f" ({reason})" if reason else ""
print("\n========== LIVE SCORE UPDATE" + tag + " ==========")
print(json.dumps(score, indent=2, sort_keys=True))
print("==================================================\n")
async def _finalize_watchdog_loop():
while True:
await asyncio.sleep(0.5)
try:
limit = float(FINAL_DEADLINE_SIM) if FINAL_DEADLINE_SIM is not None else float(TIME_LIMIT_SEC)
if sim_time() >= limit:
maybe_finalize_time_and_score()
except Exception as e:
print(f"[finalize_watchdog] ERROR: {type(e).__name__}: {e}")
# ---------------------------------
# DB Models (all times as sim-time floats)
# ---------------------------------
class Box(Base):
__tablename__ = "boxes"
id = Column(Integer, primary_key=True, autoincrement=True)
# We'll use "id" as box_id externally.
has_X = Column(Boolean, nullable=False)
has_Y = Column(Boolean, nullable=False)
senseable_X = Column(Boolean, nullable=False, default=True)
senseable_Y = Column(Boolean, nullable=False, default=True)
# Deadline as simulation time (seconds since SERVER_START)
deadline = Column(Float, nullable=False)
# Durations in seconds
sense_time_X = Column(Float, nullable=False)
sense_time_Y = Column(Float, nullable=False)
dispose_time_X = Column(Float, nullable=False)
dispose_time_Y = Column(Float, nullable=False)
# Location
x = Column(Float, nullable=False)
y = Column(Float, nullable=False)
release_time = Column(Float, nullable=False, default=0.0)
sense_results = relationship(
"SenseResult", back_populates="box", cascade="all, delete-orphan"
)
disposal_results = relationship(
"DisposalResult", back_populates="box", cascade="all, delete-orphan"
)
class SenseResult(Base):
__tablename__ = "sense_results"
id = Column(Integer, primary_key=True, autoincrement=True)
agent_id = Column(String, nullable=False)
box_id = Column(Integer, ForeignKey("boxes.id"), nullable=False)
property = Column(String, nullable=False) # "X" or "Y"
status = Column(String, nullable=False, default="running") # running/completed/cancelled
# All times as sim-time seconds
requested_at = Column(Float, nullable=False)
started_at = Column(Float, nullable=True)
completed_at = Column(Float, nullable=True)
cancelled_at = Column(Float, nullable=True)
detected = Column(Boolean, nullable=True) # sensor output
probability = Column(Float, nullable=True) # probability used to sample
duration_sec = Column(Float, nullable=True)
box = relationship("Box", back_populates="sense_results")
__table_args__ = (
Index("ix_sense_agent_box_prop", "agent_id", "box_id", "property"),
)
class DisposalResult(Base):
__tablename__ = "disposal_results"
id = Column(Integer, primary_key=True, autoincrement=True)
agent_id = Column(String, nullable=False)
box_id = Column(Integer, ForeignKey("boxes.id"), nullable=False)
property = Column(String, nullable=False) # "X" or "Y"
status = Column(String, nullable=False, default="running") # running/completed/cancelled
# All times as sim-time seconds
requested_at = Column(Float, nullable=False)
started_at = Column(Float, nullable=True)
completed_at = Column(Float, nullable=True)
cancelled_at = Column(Float, nullable=True)
success = Column(Boolean, nullable=True)
duration_sec = Column(Float, nullable=True)
box = relationship("Box", back_populates="disposal_results")
__table_args__ = (
Index("ix_dispose_agent_box_prop", "agent_id", "box_id", "property"),
)
class AgentPropertyDetectionParams(BaseModel):
present: float # P(detect=True | property present)
absent: float # P(detect=True | property absent)
class AgentDetectionParams(BaseModel):
X: AgentPropertyDetectionParams
Y: AgentPropertyDetectionParams
class AgentDetectionParamsResponse(BaseModel):
agents: Dict[str, AgentDetectionParams]
default: AgentDetectionParams
Base.metadata.create_all(engine)
def probability_reading_correct(
agent_id: str,
prop: str,
detected: bool,
prior_present: float = 0.5,
) -> float:
agent_params = AGENT_DETECTION_PARAMS.get(agent_id, DEFAULT_AGENT_PARAMS)
t = float(agent_params[prop]["present"]) # P(+ | present)
f = float(agent_params[prop]["absent"]) # P(+ | absent)
pi = max(0.0, min(1.0, float(prior_present)))
if detected:
# P(present | +)
num = t * pi
den = (t * pi) + (f * (1.0 - pi))
else:
# P(absent | -)
num = (1.0 - f) * (1.0 - pi)
den = ((1.0 - t) * pi) + ((1.0 - f) * (1.0 - pi))
if den <= 1e-12:
return 0.5
return num / den
# ---------------------------------
# Seeding: 20 random boxes (deadlines in sim time)
# ---------------------------------
# ---------------------------------
# 3) In seeding, store release_time on the Box
# ---------------------------------
def seed_boxes_if_empty():
global FINAL_DEADLINE_SIM
with SessionLocal() as db:
count = db.query(Box).count()
if count > 0:
# still compute in case it wasn't set (e.g., hot reload)
mx = db.query(func.max(Box.deadline)).scalar()
FINAL_DEADLINE_SIM = float(mx) if mx is not None else None
return
boxes: List[Box] = []
scenario_start = sim_time() # anchor deadlines + release times to this run/reset
for idx in range(1, 11):
x = objects_pre_data[idx]["x"]
y = objects_pre_data[idx]["y"]
if USE_HARDCODED_SCENARIO:
spec = SCENARIO_BOXES[idx]
has_X = bool(spec["has_X"])
has_Y = bool(spec["has_Y"])
deadline = scenario_start + float(spec["deadline_offset"])
# NEW: release time (defaults to 0 if omitted)
release_time = scenario_start + float(spec.get("release_time", 0.0))
sense_time_X = float(spec["sense_X"])
sense_time_Y = float(spec["sense_Y"])
dispose_time_X = float(spec["disp_X"])
dispose_time_Y = float(spec["disp_Y"])
if "senseable_X" in spec or "senseable_Y" in spec:
senseable_X = bool(spec.get("senseable_X", True))
senseable_Y = bool(spec.get("senseable_Y", True))
else:
allowed = spec.get("senseable", ["X", "Y"])
allowed_set = {str(p).upper() for p in allowed}
senseable_X = ("X" in allowed_set)
senseable_Y = ("Y" in allowed_set)
else:
has_X = random.random() < 0.5
has_Y = random.random() < 0.5
deadline_offset_sec = random.uniform(120, 600)
deadline = sim_time() + deadline_offset_sec
# NEW: random release (optional; here keep all available immediately)
release_time = sim_time()
sense_time_X = random.uniform(5.0, 60.0)
sense_time_Y = random.uniform(5.0, 60.0)
dispose_time_X = random.uniform(5.0, 60.0)
dispose_time_Y = random.uniform(5.0, 60.0)
senseable_X = True
senseable_Y = True
b = Box(
has_X=has_X,
has_Y=has_Y,
deadline=deadline,
sense_time_X=sense_time_X,
sense_time_Y=sense_time_Y,
dispose_time_X=dispose_time_X,
dispose_time_Y=dispose_time_Y,
x=x,
y=y,
senseable_X=senseable_X,
senseable_Y=senseable_Y,
# NEW:
release_time=float(release_time),
)
boxes.append(b)
db.add_all(boxes)
db.commit()
mx = db.query(func.max(Box.deadline)).scalar()
FINAL_DEADLINE_SIM = float(mx) if mx is not None else None
seed_boxes_if_empty()
# ---------------------------------
# In-memory registries for running ops (for immediate cancel)
# ---------------------------------
RUNNING_SENSE_OPS: Dict[int, asyncio.Event] = {}
RUNNING_DISPOSE_OPS: Dict[int, asyncio.Event] = {}
# ---------------------------------
# NEW: collaborative disposal sessions (per-box, cross-property)
# ---------------------------------
@dataclass
class SharedDisposalSession:
box_id: int
required_base_time: float # physical dispose duration (1 agent)
deadline_sim: float
lock: asyncio.Lock = field(default_factory=asyncio.Lock)
participants: set[int] = field(default_factory=set) # disposal_result ids currently helping
participant_props: Dict[int, str] = field(default_factory=dict) # disposal_result.id -> requested prop ("X"/"Y")
progress_base: float = 0.0
last_sim: Optional[float] = None
done_event: asyncio.Event = field(default_factory=asyncio.Event)
outcome: Optional[str] = None # "completed" | "deadline"
completed_at: Optional[float] = None
completed_participants: set[int] = field(default_factory=set)
completed_participant_props: Dict[int, str] = field(default_factory=dict)
task: Optional[asyncio.Task] = None
# key = box_id (NOT (box_id, prop))
DISPOSAL_SESSIONS: Dict[int, SharedDisposalSession] = {}
# map disposal_result.id -> box_id so /dispose/cancel can remove participant quickly
DISPOSE_ID_TO_SESSION: Dict[int, int] = {}
async def interruptible_sleep(duration: float, cancel_event: asyncio.Event) -> str:
"""
Wait for 'duration' seconds, but return early if cancel_event is set.
Returns:
"completed" if the full duration elapsed without cancellation.
"cancelled" if the event was set before timeout.
"""
try:
await asyncio.wait_for(cancel_event.wait(), timeout=duration)
return "cancelled"
except asyncio.TimeoutError:
return "completed"
async def interruptible_sleep_with_deadline(
duration: float,
cancel_event: asyncio.Event,
start_sim: float,
deadline_sim: float,
) -> str:
"""
Wait for up to `duration` seconds, but return early if:
- cancel_event is set -> "cancelled"
- deadline_sim is reached before duration elapses -> "deadline"
- duration elapses first -> "completed"
We compare using sim-time captured at action start:
time_to_deadline = deadline_sim - start_sim
This assumes sim-time progresses in real-time (your sim_time() does).
"""
# If we're already at/past deadline at start, deadline wins immediately.
time_to_deadline = float(deadline_sim) - float(start_sim)
if time_to_deadline <= 0.0:
return "deadline"
# Deadline and duration race: whichever occurs first.
timeout = min(float(duration), time_to_deadline)
try:
await asyncio.wait_for(cancel_event.wait(), timeout=timeout)
return "cancelled"
except asyncio.TimeoutError:
# If we timed out because we hit the deadline first
if time_to_deadline < float(duration):
return "deadline"
return "completed"
# ---------------------------------
# Pydantic Schemas (sim-time floats)
# ---------------------------------
PropertyLiteral = Literal["X", "Y"]
class SenseRequest(BaseModel):
agent_id: str = Field(..., min_length=1)
box_id: int = Field(..., ge=1)
property: PropertyLiteral
class SenseResponse(BaseModel):
agent_id: str
box_id: int
property: PropertyLiteral
status: Literal["completed", "cached", "cancelled"]
detected: Optional[bool]
probability: Optional[float]
deadline: float # sim time seconds
x: float
y: float
requested_at: float # sim time seconds
completed_at: Optional[float] # sim time seconds
class SenseCancelRequest(BaseModel):
agent_id: str
box_id: int
property: PropertyLiteral
class SenseCancelResponse(BaseModel):
agent_id: str
box_id: int
property: PropertyLiteral
status: Literal["cancelled", "not_found", "already_completed"]
class DisposeRequest(BaseModel):
agent_id: str = Field(..., min_length=1)
box_id: int = Field(..., ge=1)
property: PropertyLiteral
class DisposeResponse(BaseModel):
agent_id: str
box_id: int
property: PropertyLiteral
status: Literal["completed", "cancelled"]
success: Optional[bool]
deadline: float # sim time seconds
x: float
y: float
requested_at: float # sim time seconds
completed_at: Optional[float] # sim time seconds
class DisposeCancelRequest(BaseModel):
agent_id: str
box_id: int
property: PropertyLiteral
class DisposeCancelResponse(BaseModel):
agent_id: str
box_id: int
property: PropertyLiteral
status: Literal["cancelled", "not_found", "already_completed"]
class SenseResultView(BaseModel):
agent_id: str
property: PropertyLiteral
status: str
detected: Optional[bool]
probability: Optional[float]
completed_at: Optional[float] # sim time seconds
class DisposalResultView(BaseModel):
agent_id: str
property: PropertyLiteral
status: str
success: Optional[bool]
completed_at: Optional[float]
class BoxState(BaseModel):
box_id: int
deadline: float # sim time seconds
x: float
y: float
sense_results: List[SenseResultView]
disposed_X: bool
disposed_Y: bool
sense_time_X: float
sense_time_Y: float
dispose_time_X: float
dispose_time_Y: float
has_X: bool
has_Y: bool
disposal_results: List[DisposalResultView]
senseable_X: bool
senseable_Y: bool
class TimeResp(BaseModel):
server_time: float
time_limit_sec: float
time_up: bool
score: Optional[dict] = None
# ---------------------------------
# Helpers
# ---------------------------------
def _print_final_score_once() -> None: