File size: 3,351 Bytes
8ca7ba0
 
 
 
 
75e20e2
 
 
8ca7ba0
 
 
 
 
 
 
 
 
 
75e20e2
 
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75e20e2
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import time
from collections.abc import Callable
from dataclasses import dataclass
from typing import Generic, TypeVar

T = TypeVar('T')


@dataclass(frozen=True, slots=True)
class StackJob:
    stack_id: str
    surface_id: str
    bbox_min_xy: tuple[float, float]
    bbox_max_xy: tuple[float, float]


@dataclass(frozen=True)
class StackBatchResult(Generic[T]):
    values: dict[str, T]
    batches: list[dict[str, object]]


def group_stack_jobs(jobs: list[StackJob], margin_m: float = 0.05) -> list[list[StackJob]]:
    """Group stacks that share a support and may interact in one physics world."""

    remaining = {job.stack_id: job for job in jobs}
    groups: list[list[StackJob]] = []
    while remaining:
        _, first = remaining.popitem()
        group = [first]
        frontier = [first]
        while frontier:
            current = frontier.pop()
            touching = [
                candidate
                for candidate in remaining.values()
                if _overlaps(current, candidate, margin_m)
            ]
            for candidate in touching:
                remaining.pop(candidate.stack_id)
                group.append(candidate)
                frontier.append(candidate)
        groups.append(sorted(group, key=lambda item: item.stack_id))
    return sorted(groups, key=lambda group: group[0].stack_id)


def run_stack_batches(
    groups: list[list[StackJob]],
    run_batch: Callable[[list[StackJob]], dict[str, T]],
) -> StackBatchResult[T]:
    """Execute stack worlds with deterministic bisection down to single-stack fallback."""

    values: dict[str, T] = {}
    records: list[dict[str, object]] = []

    def run(group: list[StackJob]) -> None:
        started = time.perf_counter()
        try:
            batch_values = run_batch(group)
            expected = {item.stack_id for item in group}
            if set(batch_values) != expected:
                raise ValueError("stack simulator returned an incomplete batch")
            values.update(batch_values)
            records.append(
                {
                    "stack_ids": sorted(expected),
                    "status": "complete",
                    "duration_s": round(time.perf_counter() - started, 6),
                }
            )
        except Exception as error:
            records.append(
                {
                    "stack_ids": [item.stack_id for item in group],
                    "status": "fallback" if len(group) > 1 else "failed",
                    "duration_s": round(time.perf_counter() - started, 6),
                    "error": repr(error),
                }
            )
            if len(group) == 1:
                raise
            middle = len(group) // 2
            run(group[:middle])
            run(group[middle:])

    for group in groups:
        run(group)
    return StackBatchResult(values=values, batches=records)


def _overlaps(left: StackJob, right: StackJob, margin_m: float) -> bool:
    if left.surface_id != right.surface_id:
        return False
    return not (
        left.bbox_max_xy[0] + margin_m < right.bbox_min_xy[0]
        or right.bbox_max_xy[0] + margin_m < left.bbox_min_xy[0]
        or left.bbox_max_xy[1] + margin_m < right.bbox_min_xy[1]
        or right.bbox_max_xy[1] + margin_m < left.bbox_min_xy[1]
    )