various performance work (wip)

This commit is contained in:
Jan Petykiewicz 2026-04-01 21:29:23 -07:00
commit 71e263c527
2 changed files with 4071 additions and 326 deletions

View file

@ -1,5 +1,6 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
import numpy
@ -28,6 +29,49 @@ def _intersection_distance(origin: Port, geometry: BaseGeometry) -> float:
return float(numpy.sqrt((geometry.coords[0][0] - origin.x) ** 2 + (geometry.coords[0][1] - origin.y) ** 2))
def _bounds_overlap(
left: tuple[float, float, float, float],
right: tuple[float, float, float, float],
) -> bool:
return (
left[0] < right[2]
and left[2] > right[0]
and left[1] < right[3]
and left[3] > right[1]
)
def _has_non_touching_overlap(left: BaseGeometry, right: BaseGeometry) -> bool:
return left.intersects(right) and not left.touches(right)
def _span_to_bounds(
gx_min: int,
gy_min: int,
gx_max: int,
gy_max: int,
cell_size: float,
) -> tuple[float, float, float, float]:
return (
gx_min * cell_size,
gy_min * cell_size,
(gx_max + 1) * cell_size,
(gy_max + 1) * cell_size,
)
@dataclass(frozen=True, slots=True)
class PathVerificationDetail:
report: RoutingReport
conflicting_net_ids: tuple[str, ...] = ()
@dataclass(frozen=True, slots=True)
class DynamicCongestionDetail:
soft_overlap_count: int = 0
hits_frozen_net: bool = False
class RoutingWorld:
"""
Internal spatial state for collision detection, congestion, and verification.
@ -102,6 +146,9 @@ class RoutingWorld:
def remove_path(self, net_id: str) -> None:
self._dynamic_paths.remove_path(net_id)
def has_dynamic_paths(self) -> bool:
return bool(self._dynamic_paths.geometries)
def check_move_straight_static(self, start_port: Port, length: float, net_width: float) -> bool:
reach = self.ray_cast(
start_port,
@ -235,105 +282,383 @@ class RoutingWorld:
return False
def _check_real_congestion(self, result: ComponentResult, net_id: str) -> int:
def _check_real_congestion(
self,
result: ComponentResult,
candidates_by_net: dict[str, dict[int, tuple[int, ...]]],
frozen_net_ids: frozenset[str] = frozenset(),
) -> DynamicCongestionDetail:
if not candidates_by_net:
return DynamicCongestionDetail()
dynamic_paths = self._dynamic_paths
self._ensure_dynamic_tree()
if dynamic_paths.tree is None:
return 0
total_bounds = result.total_dilated_bounds
dynamic_bounds = dynamic_paths.bounds_array
possible_total = (
(total_bounds[0] < dynamic_bounds[:, 2])
& (total_bounds[2] > dynamic_bounds[:, 0])
& (total_bounds[1] < dynamic_bounds[:, 3])
& (total_bounds[3] > dynamic_bounds[:, 1])
)
valid_hits_mask = dynamic_paths.net_ids_array != net_id
if not numpy.any(possible_total & valid_hits_mask):
return 0
geometries_to_test = result.dilated_collision_geometry
res_indices, tree_indices = dynamic_paths.tree.query(geometries_to_test, predicate="intersects")
if tree_indices.size == 0:
return 0
hit_net_ids = numpy.take(dynamic_paths.net_ids_array, tree_indices)
unique_other_nets = numpy.unique(hit_net_ids[hit_net_ids != net_id])
if unique_other_nets.size == 0:
return 0
tree_geometries = dynamic_paths.tree.geometries
real_hits_count = 0
for other_net_id in unique_other_nets:
other_mask = hit_net_ids == other_net_id
sub_tree_indices = tree_indices[other_mask]
sub_res_indices = res_indices[other_mask]
for other_net_id, other_obj_ids in candidates_by_net.items():
found_real = False
for index in range(len(sub_tree_indices)):
if self.metrics is not None:
self.metrics.total_congestion_exact_pair_checks += 1
test_geometry = geometries_to_test[sub_res_indices[index]]
tree_geometry = tree_geometries[sub_tree_indices[index]]
if not test_geometry.touches(tree_geometry) and test_geometry.intersection(tree_geometry).area > 1e-7:
found_real = True
for obj_id, test_geometry_indexes in other_obj_ids.items():
tree_geometry = dynamic_paths.dilated[obj_id]
for test_geometry_index in test_geometry_indexes:
test_geometry = geometries_to_test[test_geometry_index]
if self.metrics is not None:
self.metrics.total_congestion_exact_pair_checks += 1
if _has_non_touching_overlap(test_geometry, tree_geometry):
found_real = True
break
if found_real:
break
if found_real:
if other_net_id in frozen_net_ids:
return DynamicCongestionDetail(
soft_overlap_count=real_hits_count,
hits_frozen_net=True,
)
real_hits_count += 1
return real_hits_count
return DynamicCongestionDetail(soft_overlap_count=real_hits_count)
def check_move_congestion(self, result: ComponentResult, net_id: str) -> int:
def _collect_congestion_candidates(
self,
result: ComponentResult,
net_id: str,
net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
broad_phase_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]] | None = None,
) -> dict[str, dict[int, tuple[int, ...]]]:
dynamic_paths = self._dynamic_paths
if not dynamic_paths.dilated:
return {}
self._ensure_dynamic_grid()
if not dynamic_paths.grid:
return {}
candidates_by_net: dict[str, dict[int, set[int]]] = {}
for test_geometry_index, test_bounds in enumerate(result.dilated_bounds):
if not self._has_possible_congestion_in_grid(test_bounds, net_id):
continue
envelope_net_ids = self._get_net_envelope_candidates(
test_bounds,
net_id,
net_envelope_cache,
)
if not envelope_net_ids:
continue
grid_net_ids = self._get_grid_span_net_candidates(
test_bounds,
net_id,
grid_net_cache,
)
if not grid_net_ids:
continue
candidate_net_ids = tuple(sorted(set(envelope_net_ids) & set(grid_net_ids)))
if not candidate_net_ids:
continue
grid_candidates = self._get_grid_span_candidates(
test_bounds,
net_id,
broad_phase_cache,
)
for other_net_id in candidate_net_ids:
if self.metrics is not None:
self.metrics.total_congestion_candidate_nets += 1
obj_ids = grid_candidates.get(other_net_id)
if not obj_ids:
continue
for obj_id in obj_ids:
if not _bounds_overlap(test_bounds, dynamic_paths.dilated_bounds[obj_id]):
continue
if self.metrics is not None:
self.metrics.total_congestion_candidate_ids += 1
candidate_indexes = candidates_by_net.setdefault(other_net_id, {}).setdefault(obj_id, set())
candidate_indexes.add(test_geometry_index)
return {
other_net_id: {
obj_id: tuple(sorted(test_geometry_indexes))
for obj_id, test_geometry_indexes in sorted(obj_ids.items())
}
for other_net_id, obj_ids in candidates_by_net.items()
}
def _has_possible_congestion_in_grid(
self,
bounds: tuple[float, float, float, float],
net_id: str,
) -> bool:
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
dynamic_paths = self._dynamic_paths
if gx_min == gx_max and gy_min == gy_max:
net_counts = dynamic_paths.grid_net_counts.get((gx_min, gy_min))
return bool(net_counts and (len(net_counts) > 1 or net_id not in net_counts))
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
net_counts = dynamic_paths.grid_net_counts.get((gx, gy))
if net_counts and (len(net_counts) > 1 or net_id not in net_counts):
return True
return False
def has_possible_move_congestion(
self,
result: ComponentResult,
net_id: str,
presence_cache: dict[tuple[str, int, int, int, int], bool] | None = None,
) -> bool:
dynamic_paths = self._dynamic_paths
if not dynamic_paths.dilated:
return False
self._ensure_dynamic_grid()
if not dynamic_paths.grid:
return False
for bounds in result.dilated_bounds:
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, gx_min, gy_min, gx_max, gy_max)
if presence_cache is not None and cache_key in presence_cache:
if self.metrics is not None:
self.metrics.total_congestion_presence_cache_hits += 1
has_possible = presence_cache[cache_key]
else:
if self.metrics is not None:
self.metrics.total_congestion_presence_cache_misses += 1
has_possible = self._has_possible_congestion_in_grid(bounds, net_id)
if presence_cache is not None:
presence_cache[cache_key] = has_possible
if has_possible:
return True
return False
def has_candidate_move_congestion(
self,
result: ComponentResult,
net_id: str,
candidate_precheck_cache: dict[tuple[str, int, int, int, int], bool] | None = None,
net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
) -> bool:
dynamic_paths = self._dynamic_paths
if not dynamic_paths.dilated:
return False
for bounds in result.dilated_bounds:
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, gx_min, gy_min, gx_max, gy_max)
if candidate_precheck_cache is not None and cache_key in candidate_precheck_cache:
if self.metrics is not None:
self.metrics.total_congestion_candidate_precheck_hits += 1
has_candidates = candidate_precheck_cache[cache_key]
else:
if self.metrics is not None:
self.metrics.total_congestion_candidate_precheck_misses += 1
span_bounds = _span_to_bounds(gx_min, gy_min, gx_max, gy_max, self.grid_cell_size)
envelope_net_ids = self._get_net_envelope_candidates(
span_bounds,
net_id,
net_envelope_cache,
)
if not envelope_net_ids:
has_candidates = False
else:
grid_net_ids = self._get_grid_span_net_candidates(
span_bounds,
net_id,
grid_net_cache,
)
if not grid_net_ids:
has_candidates = False
else:
has_candidates = bool(set(envelope_net_ids) & set(grid_net_ids))
if candidate_precheck_cache is not None:
candidate_precheck_cache[cache_key] = has_candidates
if has_candidates:
return True
return False
def _get_grid_span_candidates(
self,
bounds: tuple[float, float, float, float],
net_id: str,
broad_phase_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]] | None,
) -> dict[str, tuple[int, ...]]:
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, gx_min, gy_min, gx_max, gy_max)
if broad_phase_cache is not None and cache_key in broad_phase_cache:
if self.metrics is not None:
self.metrics.total_congestion_grid_span_cache_hits += 1
return broad_phase_cache[cache_key]
if self.metrics is not None:
self.metrics.total_congestion_grid_span_cache_misses += 1
dynamic_paths = self._dynamic_paths
candidates_by_net: dict[str, set[int]] = {}
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
for other_net_id, obj_ids in dynamic_paths.grid_net_obj_ids.get((gx, gy), {}).items():
if other_net_id == net_id:
continue
candidates_by_net.setdefault(other_net_id, set()).update(obj_ids)
frozen = {
other_net_id: tuple(sorted(obj_ids))
for other_net_id, obj_ids in sorted(candidates_by_net.items())
}
if broad_phase_cache is not None:
broad_phase_cache[cache_key] = frozen
return frozen
def _get_grid_span_net_candidates(
self,
bounds: tuple[float, float, float, float],
net_id: str,
grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None,
) -> tuple[str, ...]:
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, gx_min, gy_min, gx_max, gy_max)
if grid_net_cache is not None and cache_key in grid_net_cache:
if self.metrics is not None:
self.metrics.total_congestion_grid_net_cache_hits += 1
return grid_net_cache[cache_key]
if self.metrics is not None:
self.metrics.total_congestion_grid_net_cache_misses += 1
dynamic_paths = self._dynamic_paths
candidate_net_ids: set[str] = set()
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
for other_net_id in dynamic_paths.grid_net_obj_ids.get((gx, gy), {}):
if other_net_id != net_id:
candidate_net_ids.add(other_net_id)
frozen = tuple(sorted(candidate_net_ids))
if grid_net_cache is not None:
grid_net_cache[cache_key] = frozen
return frozen
def _get_net_envelope_candidates(
self,
bounds: tuple[float, float, float, float],
net_id: str,
net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None,
) -> tuple[str, ...]:
dynamic_paths = self._dynamic_paths
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, gx_min, gy_min, gx_max, gy_max)
if net_envelope_cache is not None and cache_key in net_envelope_cache:
if self.metrics is not None:
self.metrics.total_congestion_net_envelope_cache_hits += 1
cached_net_ids = net_envelope_cache[cache_key]
else:
if self.metrics is not None:
self.metrics.total_congestion_net_envelope_cache_misses += 1
span_bounds = _span_to_bounds(gx_min, gy_min, gx_max, gy_max, self.grid_cell_size)
cached_net_ids = tuple(
sorted(
dynamic_paths.net_envelope_obj_to_net[obj_id]
for obj_id in dynamic_paths.net_envelope_index.intersection(span_bounds)
if dynamic_paths.net_envelope_obj_to_net[obj_id] != net_id
)
)
if net_envelope_cache is not None:
net_envelope_cache[cache_key] = cached_net_ids
return tuple(
other_net_id
for other_net_id in cached_net_ids
if _bounds_overlap(bounds, dynamic_paths.net_envelopes[other_net_id])
)
def _get_verify_net_envelope_candidates(
self,
bounds: tuple[float, float, float, float],
net_id: str,
) -> tuple[str, ...]:
dynamic_paths = self._dynamic_paths
candidate_net_ids: list[str] = []
for obj_id in dynamic_paths.net_envelope_index.intersection(bounds):
other_net_id = dynamic_paths.net_envelope_obj_to_net[obj_id]
if other_net_id == net_id:
continue
if not _bounds_overlap(bounds, dynamic_paths.net_envelopes[other_net_id]):
continue
candidate_net_ids.append(other_net_id)
if self.metrics is not None:
self.metrics.total_verify_dynamic_candidate_nets += len(candidate_net_ids)
return tuple(candidate_net_ids)
def _get_verify_grid_span_obj_ids(
self,
bounds: tuple[float, float, float, float],
other_net_id: str,
) -> tuple[int, ...]:
dynamic_paths = self._dynamic_paths
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
obj_ids: set[int] = set()
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
obj_ids.update(dynamic_paths.grid_net_obj_ids.get((gx, gy), {}).get(other_net_id, ()))
return tuple(sorted(obj_ids))
def check_move_congestion(
self,
result: ComponentResult,
net_id: str,
net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
broad_phase_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]] | None = None,
) -> int:
return self.check_move_congestion_detail(
result,
net_id,
net_envelope_cache=net_envelope_cache,
grid_net_cache=grid_net_cache,
broad_phase_cache=broad_phase_cache,
).soft_overlap_count
def check_move_congestion_detail(
self,
result: ComponentResult,
net_id: str,
*,
frozen_net_ids: frozenset[str] = frozenset(),
net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
broad_phase_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]] | None = None,
) -> DynamicCongestionDetail:
if self.metrics is not None:
self.metrics.total_congestion_check_calls += 1
dynamic_paths = self._dynamic_paths
if not dynamic_paths.geometries:
return 0
return DynamicCongestionDetail()
total_bounds = result.total_dilated_bounds
self._ensure_dynamic_grid()
dynamic_grid = dynamic_paths.grid
if not dynamic_grid:
return 0
candidates_by_net = self._collect_congestion_candidates(
result,
net_id,
net_envelope_cache,
grid_net_cache,
broad_phase_cache,
)
if not candidates_by_net:
return DynamicCongestionDetail()
return self._check_real_congestion(
result,
candidates_by_net,
frozen_net_ids=frozen_net_ids,
)
gx_min, gy_min, gx_max, gy_max = grid_cell_span(total_bounds, self.grid_cell_size)
if gx_min == gx_max and gy_min == gy_max:
cell = (gx_min, gy_min)
if cell in dynamic_grid:
for obj_id in dynamic_grid[cell]:
if dynamic_paths.geometries[obj_id][0] != net_id:
return self._check_real_congestion(result, net_id)
return 0
any_possible = False
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
cell = (gx, gy)
if cell in dynamic_grid:
for obj_id in dynamic_grid[cell]:
if dynamic_paths.geometries[obj_id][0] != net_id:
any_possible = True
break
if any_possible:
break
if any_possible:
break
if not any_possible:
return 0
return self._check_real_congestion(result, net_id)
def verify_path_report(self, net_id: str, components: Sequence[ComponentResult]) -> RoutingReport:
def verify_path_details(self, net_id: str, components: Sequence[ComponentResult]) -> PathVerificationDetail:
if self.metrics is not None:
self.metrics.total_verify_path_report_calls += 1
static_collision_count = 0
dynamic_collision_count = 0
self_collision_count = 0
total_length = sum(component.length for component in components)
conflicting_net_ids: set[str] = set()
static_obstacles = self._static_obstacles
dynamic_paths = self._dynamic_paths
@ -356,43 +681,45 @@ class RoutingWorld:
if not self._is_in_safety_zone(polygon, obj_id, None, None):
static_collision_count += 1
self._ensure_dynamic_tree()
if dynamic_paths.tree is not None:
tree_geometries = dynamic_paths.tree.geometries
if dynamic_paths.dilated:
for component in components:
test_geometries = component.dilated_physical_geometry
res_indices, tree_indices = dynamic_paths.tree.query(test_geometries, predicate="intersects")
if tree_indices.size == 0:
continue
hit_net_ids = numpy.take(dynamic_paths.net_ids_array, tree_indices)
component_hits = []
for index in range(len(tree_indices)):
if hit_net_ids[index] == str(net_id):
continue
if self.metrics is not None:
self.metrics.total_verify_dynamic_exact_pair_checks += 1
new_geometry = test_geometries[res_indices[index]]
tree_geometry = tree_geometries[tree_indices[index]]
if not new_geometry.touches(tree_geometry) and new_geometry.intersection(tree_geometry).area > 1e-7:
component_hits.append(hit_net_ids[index])
for new_geometry in test_geometries:
for hit_net_id in self._get_verify_net_envelope_candidates(new_geometry.bounds, str(net_id)):
for obj_id in self._get_verify_grid_span_obj_ids(new_geometry.bounds, hit_net_id):
if not _bounds_overlap(new_geometry.bounds, dynamic_paths.dilated_bounds[obj_id]):
continue
if self.metrics is not None:
self.metrics.total_verify_dynamic_exact_pair_checks += 1
tree_geometry = dynamic_paths.dilated[obj_id]
if _has_non_touching_overlap(new_geometry, tree_geometry):
component_hits.append(hit_net_id)
break
if component_hits:
dynamic_collision_count += len(numpy.unique(component_hits))
unique_hits = tuple(sorted(set(component_hits)))
dynamic_collision_count += len(unique_hits)
conflicting_net_ids.update(unique_hits)
for index, component in enumerate(components):
for other_index in range(index + 2, len(components)):
if components_overlap(component, components[other_index], prefer_actual=True):
self_collision_count += 1
return RoutingReport(
static_collision_count=static_collision_count,
dynamic_collision_count=dynamic_collision_count,
self_collision_count=self_collision_count,
total_length=total_length,
return PathVerificationDetail(
report=RoutingReport(
static_collision_count=static_collision_count,
dynamic_collision_count=dynamic_collision_count,
self_collision_count=self_collision_count,
total_length=total_length,
),
conflicting_net_ids=tuple(sorted(conflicting_net_ids)),
)
def verify_path_report(self, net_id: str, components: Sequence[ComponentResult]) -> RoutingReport:
return self.verify_path_details(net_id, components).report
def ray_cast(
self,
origin: Port,

View file

@ -22,9 +22,18 @@ class DynamicPathIndex:
"index",
"geometries",
"dilated",
"dilated_bounds",
"net_envelope_index",
"net_envelopes",
"net_envelope_obj_ids",
"net_envelope_obj_to_net",
"tree",
"obj_ids",
"grid",
"grid_net_obj_ids",
"grid_net_counts",
"obj_cells",
"net_to_obj_ids",
"id_counter",
"net_ids_array",
"bounds_array",
@ -35,16 +44,69 @@ class DynamicPathIndex:
self.index = rtree.index.Index()
self.geometries: dict[int, tuple[str, Polygon]] = {}
self.dilated: dict[int, Polygon] = {}
self.dilated_bounds: dict[int, tuple[float, float, float, float]] = {}
self.net_envelope_index = rtree.index.Index()
self.net_envelopes: dict[str, tuple[float, float, float, float]] = {}
self.net_envelope_obj_ids: dict[str, int] = {}
self.net_envelope_obj_to_net: dict[int, str] = {}
self.tree: STRtree | None = None
self.obj_ids: numpy.ndarray = numpy.array([], dtype=numpy.int32)
self.grid: dict[tuple[int, int], list[int]] = {}
self.grid_net_obj_ids: dict[tuple[int, int], dict[str, set[int]]] = {}
self.grid_net_counts: dict[tuple[int, int], dict[str, int]] = {}
self.obj_cells: dict[int, tuple[tuple[int, int], ...]] = {}
self.net_to_obj_ids: dict[str, set[int]] = {}
self.id_counter = 0
self.net_ids_array = numpy.array([], dtype=object)
self.bounds_array = numpy.array([], dtype=numpy.float64).reshape(0, 4)
def _combine_net_bounds(self, obj_ids: set[int]) -> tuple[float, float, float, float]:
first_obj_id = next(iter(obj_ids))
minx, miny, maxx, maxy = self.dilated_bounds[first_obj_id]
for obj_id in obj_ids:
bounds = self.dilated_bounds[obj_id]
minx = min(minx, bounds[0])
miny = min(miny, bounds[1])
maxx = max(maxx, bounds[2])
maxy = max(maxy, bounds[3])
return (minx, miny, maxx, maxy)
def _set_net_envelope(self, net_id: str, bounds: tuple[float, float, float, float]) -> None:
old_bounds = self.net_envelopes.get(net_id)
if old_bounds is not None:
obj_id = self.net_envelope_obj_ids[net_id]
self.net_envelope_index.delete(obj_id, old_bounds)
else:
obj_id = len(self.net_envelope_obj_ids)
while obj_id in self.net_envelope_obj_to_net:
obj_id += 1
self.net_envelope_obj_ids[net_id] = obj_id
self.net_envelope_obj_to_net[obj_id] = net_id
self.net_envelopes[net_id] = bounds
self.net_envelope_index.insert(self.net_envelope_obj_ids[net_id], bounds)
def _clear_net_envelope(self, net_id: str) -> None:
old_bounds = self.net_envelopes.pop(net_id, None)
obj_id = self.net_envelope_obj_ids.pop(net_id, None)
if old_bounds is None or obj_id is None:
return
self.net_envelope_index.delete(obj_id, old_bounds)
self.net_envelope_obj_to_net.pop(obj_id, None)
def _refresh_net_envelope(self, net_id: str) -> None:
obj_ids = self.net_to_obj_ids.get(net_id)
if not obj_ids:
self._clear_net_envelope(net_id)
return
self._set_net_envelope(net_id, self._combine_net_bounds(obj_ids))
def invalidate_queries(self) -> None:
self.tree = None
self.grid = {}
self.grid_net_obj_ids = {}
self.grid_net_counts = {}
self.obj_cells = {}
def ensure_tree(self) -> None:
if self.tree is None and self.dilated:
@ -65,33 +127,97 @@ class DynamicPathIndex:
self.engine.metrics.total_dynamic_grid_rebuilds += 1
cell_size = self.engine.grid_cell_size
for obj_id, polygon in self.dilated.items():
for cell in iter_grid_cells(polygon.bounds, cell_size):
self.grid.setdefault(cell, []).append(obj_id)
self._register_grid_membership(obj_id, self.geometries[obj_id][0], polygon.bounds, cell_size=cell_size)
def _register_grid_membership(
self,
obj_id: int,
net_id: str,
bounds: tuple[float, float, float, float],
*,
cell_size: float,
) -> None:
cells = tuple(iter_grid_cells(bounds, cell_size))
self.obj_cells[obj_id] = cells
for cell in cells:
self.grid.setdefault(cell, []).append(obj_id)
net_obj_ids = self.grid_net_obj_ids.setdefault(cell, {})
net_obj_ids.setdefault(net_id, set()).add(obj_id)
net_counts = self.grid_net_counts.setdefault(cell, {})
net_counts[net_id] = net_counts.get(net_id, 0) + 1
def _unregister_grid_membership(self, obj_id: int, net_id: str) -> None:
cells = self.obj_cells.pop(obj_id, ())
for cell in cells:
obj_ids = self.grid.get(cell)
if obj_ids is not None:
try:
obj_ids.remove(obj_id)
except ValueError:
pass
if not obj_ids:
self.grid.pop(cell, None)
net_obj_ids = self.grid_net_obj_ids.get(cell)
if net_obj_ids is not None:
member_ids = net_obj_ids.get(net_id)
if member_ids is not None:
member_ids.discard(obj_id)
if not member_ids:
net_obj_ids.pop(net_id, None)
if not net_obj_ids:
self.grid_net_obj_ids.pop(cell, None)
net_counts = self.grid_net_counts.get(cell)
if net_counts is not None:
remaining = net_counts.get(net_id, 0) - 1
if remaining > 0:
net_counts[net_id] = remaining
else:
net_counts.pop(net_id, None)
if not net_counts:
self.grid_net_counts.pop(cell, None)
def add_path(self, net_id: str, geometry: Sequence[Polygon], dilated_geometry: Sequence[Polygon]) -> None:
self.invalidate_queries()
if self.engine.metrics is not None:
self.engine.metrics.total_dynamic_path_objects_added += len(geometry)
cell_size = self.engine.grid_cell_size
for index, polygon in enumerate(geometry):
obj_id = self.id_counter
self.id_counter += 1
dilated = dilated_geometry[index]
dilated_bounds = dilated.bounds
self.geometries[obj_id] = (net_id, polygon)
self.dilated[obj_id] = dilated
self.index.insert(obj_id, dilated.bounds)
self.dilated_bounds[obj_id] = dilated_bounds
self.index.insert(obj_id, dilated_bounds)
self.net_to_obj_ids.setdefault(net_id, set()).add(obj_id)
self._register_grid_membership(obj_id, net_id, dilated_bounds, cell_size=cell_size)
self._refresh_net_envelope(net_id)
self.tree = None
def remove_path(self, net_id: str) -> None:
to_remove = [obj_id for obj_id, (existing_net_id, _) in self.geometries.items() if existing_net_id == net_id]
to_remove = list(self.net_to_obj_ids.get(net_id, ()))
self.remove_obj_ids(to_remove)
def remove_obj_ids(self, obj_ids: list[int]) -> None:
if not obj_ids:
return
self.invalidate_queries()
if self.engine.metrics is not None:
self.engine.metrics.total_dynamic_path_objects_removed += len(obj_ids)
affected_nets: set[str] = set()
for obj_id in obj_ids:
self.index.delete(obj_id, self.dilated[obj_id].bounds)
net_id, _ = self.geometries[obj_id]
affected_nets.add(net_id)
self._unregister_grid_membership(obj_id, net_id)
self.index.delete(obj_id, self.dilated_bounds[obj_id])
del self.geometries[obj_id]
del self.dilated[obj_id]
del self.dilated_bounds[obj_id]
obj_id_set = self.net_to_obj_ids.get(net_id)
if obj_id_set is not None:
obj_id_set.discard(obj_id)
if not obj_id_set:
self.net_to_obj_ids.pop(net_id, None)
for net_id in affected_nets:
self._refresh_net_envelope(net_id)
self.tree = None