cooptools 1.80__tar.gz → 1.82__tar.gz
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.
- {cooptools-1.80 → cooptools-1.82}/PKG-INFO +4 -1
- {cooptools-1.80 → cooptools-1.82}/cooptools/geometry_utils/polygon_utils.py +38 -1
- {cooptools-1.80 → cooptools-1.82}/cooptools/pathing/straightLineFollower.py +11 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/pathing/waypointFollower.py +24 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/sectors/sectorTree/sectorTree.py +6 -0
- cooptools-1.82/cooptools/spatial/__init__.py +10 -0
- cooptools-1.82/cooptools/spatial/colliders.py +79 -0
- cooptools-1.82/cooptools/spatial/index.py +424 -0
- cooptools-1.82/cooptools/spatial/stores.py +220 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools.egg-info/PKG-INFO +4 -1
- {cooptools-1.80 → cooptools-1.82}/cooptools.egg-info/SOURCES.txt +6 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools.egg-info/requires.txt +3 -0
- {cooptools-1.80 → cooptools-1.82}/setup.py +4 -1
- cooptools-1.82/tests/test_polygon_utils.py +62 -0
- cooptools-1.82/tests/test_spatial_index.py +511 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_straightLineFollower.py +13 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_waypointFollower.py +78 -0
- {cooptools-1.80 → cooptools-1.82}/MANIFEST.in +0 -0
- {cooptools-1.80 → cooptools-1.82}/README.md +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/anchor.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/asyncable.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/cli/CliAtomicUserInteraction.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/cli/CliMenu.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/cli/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/cli/fileContentReturn.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/cnxn_info.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/colors.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/commandDesignPattern/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/commandDesignPattern/commandController.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/commandDesignPattern/commandProtocol.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/commandDesignPattern/exceptions.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/common.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/config.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/coopDataclass.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/coopEnum.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/coopthreading.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/currency.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/dataRefresher/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/dataRefresher/dataHub.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/dataRefresher/dataRefresher.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/dataStore/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/dataStore/dataProcessor.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/dataStore/dataStoreProtocol.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/dataStore/dbConnectionURI.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/dataStore/inMemoryDataStore.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/date_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/decay.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/decor.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/dictPolicies.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/exceptions.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/expertise/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/expertise/expertiseArgs.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/expertise/expertiseSchedules.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/expertise/expertise_state.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/finance/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/finance/dicounted_cashflow_analysis.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/finance/fund_projection.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/finance/fund_projection_renderer.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/finance/futureValueProjector.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/finance/growth_projections.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/finance/reports.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/finance/utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/geometry_utils/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/geometry_utils/circle_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/geometry_utils/common.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/geometry_utils/curve_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/geometry_utils/curves.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/geometry_utils/line_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/geometry_utils/rect_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/geometry_utils/triangle_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/geometry_utils/vector_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/graphs/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/graphs/astar_results_viewer.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/graphs/draw.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/graphs/flow_field.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/graphs/graph.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/graphs/graph_dcs.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/graphs/graph_definitions.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/graphs/utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/ideas/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/ideas/actionItemTracker/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/ideas/actionItemTracker/ai_tracker.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/ideas/actionItemTracker/dcs.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/ideas/discreteEventSimulator/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/ideas/discreteEventSimulator/discreteEventSimulator.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/ideas/jsonIO.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/ideas/metrics.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/ideas/triggerActionSystem/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/ideas/triggerActionSystem/signal.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/ideas/triggerActionSystem/trigger.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/loggingHelpers.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/marchingSquares.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/materialHandling/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/materialHandling/cli.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/materialHandling/dcs.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/materialHandling/selectionCriteria.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/matrixManipulation.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/os_manip.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/pandasHelpers.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/pathing/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/pathing/catmullRomFollower.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/pathing/demo/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/pathing/demo/server.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/pathing/kinematicGoalSeeker.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/pathing/motion_profile_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/pathing/orbit_fuzzer.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/pathing/path_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/pathing/trajectory_provider.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/pathing/waypoint.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/persistence/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/persistence/enum_state.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/persistence/stateful.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/physics/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/physics/kinematic.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/physics/kinematic_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/physics/movement.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/physics/trajectory.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/plotting.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/printing.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/protocols.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/qualifiers/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/qualifiers/cli.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/qualifiers/qualifier.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/randoms.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/register.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/reservation/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/reservation/dcs.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/reservation/enums.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/reservation/reservationmanager.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/retry.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/sectors/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/sectors/grids/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/sectors/grids/gridState.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/sectors/grids/grid_base.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/sectors/grids/hexGrid.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/sectors/grids/rectGrid.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/sectors/hex_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/sectors/sect_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/sectors/sectorTree/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/statistics/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/statistics/activityReport.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/statistics/controlChart/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/statistics/controlChart/controlChart.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/statistics/controlChart/plotting.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/statistics/oee/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/statistics/oee/oeeHub.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/taskProcessing/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/taskProcessing/dcs.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/taskProcessing/taskProcessor.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/timeTracker/__init__.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/timeTracker/decay.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/timeTracker/timeTracker.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/timeWindow.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/toggles.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/transform.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/trends.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/typeProviders.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/typevalidation.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools/version.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools.egg-info/dependency_links.txt +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools.egg-info/not-zip-safe +0 -0
- {cooptools-1.80 → cooptools-1.82}/cooptools.egg-info/top_level.txt +0 -0
- {cooptools-1.80 → cooptools-1.82}/requirements.txt +0 -0
- {cooptools-1.80 → cooptools-1.82}/setup.cfg +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_CliAtomicUserInteraction.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_asyncable.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_catmullRomFollower.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_cdp_bugs.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_commandDesignPattern.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_common.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_config.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_coopEnum.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_currency.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_curves.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_date_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_expertise_state.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_flow_field.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_flow_field_perf.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_fund_projection.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_graph_node_classification.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_kinematicGoalSeeker.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_kinematic_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_os_manip.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_pandas.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_path_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_persistence.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_printing.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_qualifiers.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_sectors.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_sectors_hex.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_sectors_sectorTree.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_statistics.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_target_seek.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_tasks.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_toggles.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_trajectory.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_trends.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_typevalidation.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_vector_utils.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/test_version.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/tests_graph.py +0 -0
- {cooptools-1.80 → cooptools-1.82}/tests/tests_gridsystem.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: cooptools
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.82
|
|
4
4
|
Summary: Generic Tooling
|
|
5
5
|
Home-page: https://github.com/tylertjburns/cooptools
|
|
6
6
|
Author: tburns
|
|
@@ -21,6 +21,8 @@ Requires-Dist: pandas>=2.2.3
|
|
|
21
21
|
Requires-Dist: pytz>=2024.1
|
|
22
22
|
Requires-Dist: Pypubsub>=4.0.3
|
|
23
23
|
Requires-Dist: python-dateutil>=2.9.0
|
|
24
|
+
Provides-Extra: spatial
|
|
25
|
+
Requires-Dist: shapely>=2.1.2; extra == "spatial"
|
|
24
26
|
Dynamic: author
|
|
25
27
|
Dynamic: author-email
|
|
26
28
|
Dynamic: classifier
|
|
@@ -28,6 +30,7 @@ Dynamic: description
|
|
|
28
30
|
Dynamic: description-content-type
|
|
29
31
|
Dynamic: home-page
|
|
30
32
|
Dynamic: license
|
|
33
|
+
Dynamic: provides-extra
|
|
31
34
|
Dynamic: requires-dist
|
|
32
35
|
Dynamic: requires-python
|
|
33
36
|
Dynamic: summary
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import math
|
|
2
|
+
from typing import Optional, Tuple
|
|
1
3
|
from cooptools.geometry_utils import vector_utils as vec
|
|
2
4
|
from cooptools.geometry_utils import line_utils as lin
|
|
5
|
+
|
|
3
6
|
def sides_in_poly(poly: vec.IterVec):
|
|
4
7
|
for i1 in range(len(poly)):
|
|
5
8
|
if i1 == len(poly) - 1:
|
|
@@ -43,7 +46,7 @@ def point_in_poly(point: vec.FloatVec, poly: vec.IterVec) -> bool:
|
|
|
43
46
|
def do_convex_polygons_intersect(poly_a: vec.IterVec, poly_b: vec.IterVec):
|
|
44
47
|
#https: // stackoverflow.com / questions / 10962379 / how - to - check - intersection - between - 2 - rotated - rectangles
|
|
45
48
|
for polygon in [poly_a, poly_b]:
|
|
46
|
-
for i1 in range(len(
|
|
49
|
+
for i1 in range(len(polygon)):
|
|
47
50
|
i2 = (i1 + 1) % len(polygon)
|
|
48
51
|
p1 = polygon[i1]
|
|
49
52
|
p2 = polygon[i2]
|
|
@@ -75,6 +78,40 @@ def do_convex_polygons_intersect(poly_a: vec.IterVec, poly_b: vec.IterVec):
|
|
|
75
78
|
return True
|
|
76
79
|
|
|
77
80
|
|
|
81
|
+
def _project(poly: vec.IterVec, axis: vec.FloatVec) -> Tuple[float, float]:
|
|
82
|
+
projections = [p[0] * axis[0] + p[1] * axis[1] for p in poly]
|
|
83
|
+
return min(projections), max(projections)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def minimum_translation_vector(poly_a: vec.IterVec, poly_b: vec.IterVec) -> Optional[vec.FloatVec]:
|
|
87
|
+
"""The shortest move that takes convex `poly_a` clear of convex `poly_b`, or None
|
|
88
|
+
when they do not overlap (polygons that only touch do not overlap).
|
|
89
|
+
|
|
90
|
+
A separating-axis test over both polygons' unit edge normals: on each axis the
|
|
91
|
+
escape is the smaller of pushing `poly_a` past either end of `poly_b`, and the
|
|
92
|
+
axis with the smallest escape gives the vector."""
|
|
93
|
+
best: Optional[Tuple[float, vec.FloatVec]] = None
|
|
94
|
+
for polygon in (poly_a, poly_b):
|
|
95
|
+
for p1, p2 in sides_in_poly(polygon):
|
|
96
|
+
length = math.hypot(p2[0] - p1[0], p2[1] - p1[1])
|
|
97
|
+
if length == 0:
|
|
98
|
+
continue
|
|
99
|
+
axis = ((p2[1] - p1[1]) / length, (p1[0] - p2[0]) / length)
|
|
100
|
+
min_a, max_a = _project(poly_a, axis)
|
|
101
|
+
min_b, max_b = _project(poly_b, axis)
|
|
102
|
+
forward = max_b - min_a # moving a along +axis until its min clears b's max
|
|
103
|
+
backward = max_a - min_b # moving a along -axis until its max clears b's min
|
|
104
|
+
if forward <= 0 or backward <= 0:
|
|
105
|
+
return None
|
|
106
|
+
if forward <= backward:
|
|
107
|
+
candidate = (forward, (axis[0] * forward, axis[1] * forward))
|
|
108
|
+
else:
|
|
109
|
+
candidate = (backward, (-axis[0] * backward, -axis[1] * backward))
|
|
110
|
+
if best is None or candidate[0] < best[0]:
|
|
111
|
+
best = candidate
|
|
112
|
+
return best[1] if best is not None else None
|
|
113
|
+
|
|
114
|
+
|
|
78
115
|
if __name__ == "__main__":
|
|
79
116
|
def test01():
|
|
80
117
|
ret = do_convex_polygons_intersect(
|
|
@@ -125,6 +125,17 @@ class StraightLineFollower:
|
|
|
125
125
|
self._max_acceleration = max_acceleration
|
|
126
126
|
self._v_max = velocity_magnitude_bounds[1] if velocity_magnitude_bounds is not None else None
|
|
127
127
|
|
|
128
|
+
@property
|
|
129
|
+
def MaxSpeed(self) -> Optional[float]:
|
|
130
|
+
"""The speed cap every plan obeys; None for no cap."""
|
|
131
|
+
return self._v_max
|
|
132
|
+
|
|
133
|
+
@MaxSpeed.setter
|
|
134
|
+
def MaxSpeed(self, value: Optional[float]):
|
|
135
|
+
"""Takes effect from the next plan: a follower already moving keeps its current
|
|
136
|
+
trajectory until it replans (`WaypointFollower.replan()` forces one)."""
|
|
137
|
+
self._v_max = value
|
|
138
|
+
|
|
128
139
|
def plan(self,
|
|
129
140
|
start_pos: vec.FloatVec,
|
|
130
141
|
start_velocity: vec.FloatVec,
|
|
@@ -105,6 +105,30 @@ class WaypointFollower:
|
|
|
105
105
|
self._pending_override_velocity = velocity
|
|
106
106
|
self._needs_replan = True
|
|
107
107
|
|
|
108
|
+
def replan(self) -> None:
|
|
109
|
+
"""Plans afresh from the current position and velocity on the next update(),
|
|
110
|
+
for when the trajectory provider's limits have changed (a lower speed cap)."""
|
|
111
|
+
self._needs_replan = True
|
|
112
|
+
|
|
113
|
+
def nudge(self, offset: vec.FloatVec, absorb_velocity: bool = True) -> None:
|
|
114
|
+
"""Shifts the position by `offset` immediately, as an outside push (a collision)
|
|
115
|
+
would, and replans from there on the next update(). Works whether or not any
|
|
116
|
+
waypoints are queued.
|
|
117
|
+
|
|
118
|
+
With `absorb_velocity`, the part of the velocity heading against the push is
|
|
119
|
+
dropped, so a follower pressed into an obstacle stops at it rather than keeping
|
|
120
|
+
full speed it cannot use; motion along or away from the push is kept."""
|
|
121
|
+
self._pos = tuple(p + o for p, o in zip(self._pos, offset))
|
|
122
|
+
if self._pending_override_pos is not None:
|
|
123
|
+
self._pending_override_pos = tuple(p + o for p, o in zip(self._pending_override_pos, offset))
|
|
124
|
+
if absorb_velocity:
|
|
125
|
+
direction = vec.unit_vector(offset)
|
|
126
|
+
if direction is not None:
|
|
127
|
+
into = vec.dot(self._velocity_vec, direction)
|
|
128
|
+
if into < 0:
|
|
129
|
+
self._velocity_vec = tuple(v - into * d for v, d in zip(self._velocity_vec, direction))
|
|
130
|
+
self._needs_replan = True
|
|
131
|
+
|
|
108
132
|
def stop(self):
|
|
109
133
|
dim = len(self._pos)
|
|
110
134
|
self._velocity_vec = vec.zero_vector(dim)
|
|
@@ -234,6 +234,12 @@ class SectorTree:
|
|
|
234
234
|
def nearby_clients(self,
|
|
235
235
|
radius: float, pt: Tuple[float, float],
|
|
236
236
|
client_types: Iterable[str] = None) -> Dict[Any, Tuple[float, float]]:
|
|
237
|
+
"""
|
|
238
|
+
Clients in sectors near `pt`; polygons are tested by bounding box only.
|
|
239
|
+
|
|
240
|
+
For exact proximity, containment or nearest-neighbour questions over
|
|
241
|
+
moving clients, use `cooptools.spatial.SpatialIndex`.
|
|
242
|
+
"""
|
|
237
243
|
t0 = time.perf_counter()
|
|
238
244
|
|
|
239
245
|
sectors_nearby = self._sectors_potentially_overlaps_radius(radius, pt)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Spatial indexing over mixed point and polygon colliders.
|
|
3
|
+
|
|
4
|
+
Needs the `spatial` extra: `pip install cooptools[spatial]`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from cooptools.spatial.colliders import Collider, to_geometry
|
|
8
|
+
from cooptools.spatial.index import KindStats, SpatialIndex, SpatialIndexStats
|
|
9
|
+
|
|
10
|
+
__all__ = ["Collider", "KindStats", "SpatialIndex", "SpatialIndexStats", "to_geometry"]
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Turning the loose shapes callers hand in into points and shapely geometry."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import numbers
|
|
5
|
+
from typing import Sequence, Tuple, Union
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import shapely
|
|
9
|
+
from shapely.geometry import Point, Polygon
|
|
10
|
+
from shapely.geometry.base import BaseGeometry
|
|
11
|
+
|
|
12
|
+
Collider = Union[BaseGeometry, Tuple[float, float], Sequence[Tuple[float, float]]]
|
|
13
|
+
XY = Tuple[float, float]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def parse(collider: Collider) -> Union[XY, BaseGeometry]:
|
|
17
|
+
"""
|
|
18
|
+
Read a collider's structure without validating any geometry.
|
|
19
|
+
|
|
20
|
+
- (x, y), [(x, y)], or a shapely Point -> an (x, y) tuple
|
|
21
|
+
- [(x, y), (x, y), (x, y), ...] -> Polygon
|
|
22
|
+
- any other shapely geometry -> used as-is
|
|
23
|
+
|
|
24
|
+
Points come back as plain coordinates because that is all the point store
|
|
25
|
+
keeps; building a shapely Point per moving client would cost more than
|
|
26
|
+
storing it. Two coordinate pairs are refused rather than guessed at: a
|
|
27
|
+
segment is a LineString, and the caller should say so.
|
|
28
|
+
"""
|
|
29
|
+
if isinstance(collider, BaseGeometry):
|
|
30
|
+
if isinstance(collider, Point) and not collider.is_empty:
|
|
31
|
+
return _finite(collider.x, collider.y)
|
|
32
|
+
return collider
|
|
33
|
+
|
|
34
|
+
coords = list(collider)
|
|
35
|
+
if not coords:
|
|
36
|
+
raise ValueError("collider is empty")
|
|
37
|
+
if isinstance(coords[0], numbers.Real):
|
|
38
|
+
if len(coords) != 2:
|
|
39
|
+
raise ValueError(f"a flat collider must be (x, y), got {len(coords)} values")
|
|
40
|
+
return _finite(coords[0], coords[1])
|
|
41
|
+
if len(coords) == 1:
|
|
42
|
+
return _finite(coords[0][0], coords[0][1])
|
|
43
|
+
if len(coords) == 2:
|
|
44
|
+
raise ValueError("two coordinate pairs is a segment; pass a shapely LineString")
|
|
45
|
+
return Polygon(coords)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def validate_shapes(geoms: Sequence[BaseGeometry]) -> None:
|
|
49
|
+
"""
|
|
50
|
+
Refuse empty or invalid geometry, checking the whole batch in one call.
|
|
51
|
+
|
|
52
|
+
Invalid geometry (a self-intersecting ring, say) is refused because
|
|
53
|
+
predicates evaluated against it return wrong answers without raising, and
|
|
54
|
+
by query time nothing points back at the client that caused it.
|
|
55
|
+
"""
|
|
56
|
+
if not len(geoms):
|
|
57
|
+
return
|
|
58
|
+
arr = np.asarray(geoms, dtype=object)
|
|
59
|
+
bad = np.flatnonzero(shapely.is_empty(arr) | ~shapely.is_valid(arr))
|
|
60
|
+
if len(bad):
|
|
61
|
+
g = arr[bad[0]]
|
|
62
|
+
reason = "empty" if g.is_empty else f"invalid: {shapely.is_valid_reason(g)}"
|
|
63
|
+
raise ValueError(f"collider geometry is {reason}")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def to_geometry(collider: Collider) -> BaseGeometry:
|
|
67
|
+
"""A collider as one valid, non-empty shapely geometry."""
|
|
68
|
+
parsed = parse(collider)
|
|
69
|
+
if isinstance(parsed, tuple):
|
|
70
|
+
return Point(parsed)
|
|
71
|
+
validate_shapes([parsed])
|
|
72
|
+
return parsed
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _finite(x, y) -> XY:
|
|
76
|
+
x, y = float(x), float(y)
|
|
77
|
+
if not (math.isfinite(x) and math.isfinite(y)):
|
|
78
|
+
raise ValueError(f"point collider has a non-finite coordinate: ({x}, {y})")
|
|
79
|
+
return x, y
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from typing import (Callable, Dict, Generic, Hashable, Iterable, Iterator, List, Mapping, Optional, Sequence, Set,
|
|
4
|
+
Tuple, TypeVar, Union)
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import shapely
|
|
8
|
+
from shapely.geometry import Point
|
|
9
|
+
from shapely.geometry.base import BaseGeometry
|
|
10
|
+
|
|
11
|
+
from cooptools.spatial.colliders import Collider, parse, to_geometry, validate_shapes
|
|
12
|
+
from cooptools.spatial.stores import Bounds, PointStore, ShapeStore
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
K = TypeVar("K", bound=Hashable)
|
|
17
|
+
Kinds = Union[None, Hashable, Iterable[Hashable]]
|
|
18
|
+
Store = Union[PointStore, ShapeStore]
|
|
19
|
+
|
|
20
|
+
# Stands in for "no client to leave out" so a client whose id is None is not.
|
|
21
|
+
_NOBODY = object()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class KindStats:
|
|
26
|
+
points: int
|
|
27
|
+
shapes: int
|
|
28
|
+
tree_rebuilds: int
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class SpatialIndexStats:
|
|
33
|
+
clients: int
|
|
34
|
+
generation: int
|
|
35
|
+
kinds: Dict[Hashable, KindStats] = field(default_factory=dict)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class _Layout:
|
|
40
|
+
"""Where each id in one id list lives, valid while `version` matches the index's."""
|
|
41
|
+
uids: List[Hashable]
|
|
42
|
+
version: int
|
|
43
|
+
groups: List[Tuple[PointStore, np.ndarray, np.ndarray]] # store, its rows, positions in uids
|
|
44
|
+
point_pos: np.ndarray
|
|
45
|
+
point_ids: List[Hashable]
|
|
46
|
+
others: List[Hashable] # ids that are not point clients
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class SpatialIndex(Generic[K]):
|
|
50
|
+
"""
|
|
51
|
+
A spatial index over any mix of point and polygon clients.
|
|
52
|
+
|
|
53
|
+
Each client is an id with one collider and one kind. The index picks where
|
|
54
|
+
to keep it: points go in a numpy array that a move writes into directly;
|
|
55
|
+
every other geometry goes in an STRtree that is rebuilt on the first query
|
|
56
|
+
after it changes. Storage is partitioned by kind, so filtering by kind
|
|
57
|
+
costs nothing. The caller never chooses a store, and every question is
|
|
58
|
+
answered across both.
|
|
59
|
+
|
|
60
|
+
Geometry is pushed in (`upsert`) or pulled from `collider_provider`
|
|
61
|
+
(`refresh`). The index never calls the provider during a query: a tree is
|
|
62
|
+
only valid while the index knows which clients changed, and asking every
|
|
63
|
+
provider on every question is the per-client Python cost this exists to
|
|
64
|
+
avoid. Tell it what changed.
|
|
65
|
+
|
|
66
|
+
Semantics:
|
|
67
|
+
- Distances are exact; a point inside a polygon is at distance 0.
|
|
68
|
+
- Boundaries count: a point on an edge shared by two polygons is in both.
|
|
69
|
+
- A query given as a client id never returns that client.
|
|
70
|
+
- Where a query could be read either way, a known client id wins over a
|
|
71
|
+
collider, so a tuple id that looks like a coordinate is the client.
|
|
72
|
+
- `kinds` is a single kind or an iterable of kinds; None means every kind.
|
|
73
|
+
|
|
74
|
+
Not thread-safe.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(self, collider_provider: Optional[Callable[[K], Collider]] = None):
|
|
78
|
+
self._provider = collider_provider
|
|
79
|
+
self._kind: Dict[K, Hashable] = {}
|
|
80
|
+
self._seq: Dict[K, int] = {}
|
|
81
|
+
self._where: Dict[K, Store] = {}
|
|
82
|
+
self._points: Dict[Hashable, PointStore] = {}
|
|
83
|
+
self._shapes: Dict[Hashable, ShapeStore] = {}
|
|
84
|
+
self._next_seq = 0
|
|
85
|
+
self._layout_version = 0
|
|
86
|
+
self._layout_cache: Optional[_Layout] = None
|
|
87
|
+
self.generation = 0
|
|
88
|
+
|
|
89
|
+
# ── Mutation ──────────────────────────────────────────────────────────────
|
|
90
|
+
|
|
91
|
+
def upsert(self, uid: K, collider: Optional[Collider] = None, kind: Optional[Hashable] = None) -> None:
|
|
92
|
+
"""
|
|
93
|
+
Add a client or replace its geometry.
|
|
94
|
+
|
|
95
|
+
`collider=None` pulls the geometry from the provider. `kind=None` keeps
|
|
96
|
+
an existing client's kind and tags a new client with the kind None.
|
|
97
|
+
"""
|
|
98
|
+
self._upsert_batch([(uid, collider)], kind)
|
|
99
|
+
|
|
100
|
+
def upsert_many(self, colliders: Mapping[K, Optional[Collider]], kind: Optional[Hashable] = None) -> None:
|
|
101
|
+
"""`upsert` for many clients. If any collider is refused, none are applied."""
|
|
102
|
+
self._upsert_batch(list(colliders.items()), kind)
|
|
103
|
+
|
|
104
|
+
def refresh(self, uids: Optional[Iterable[K]] = None) -> None:
|
|
105
|
+
"""Re-pull geometry from the provider for `uids`, or for every client."""
|
|
106
|
+
if self._provider is None:
|
|
107
|
+
raise ValueError("refresh() needs a collider_provider")
|
|
108
|
+
self._upsert_batch([(uid, None) for uid in (list(self._kind) if uids is None else uids)], None)
|
|
109
|
+
|
|
110
|
+
def move_points(self, uids: Sequence[K], xy) -> None:
|
|
111
|
+
"""
|
|
112
|
+
Move existing point clients to new coordinates in bulk.
|
|
113
|
+
|
|
114
|
+
`xy` is anything numpy reads as one (x, y) row per id. Every id must be
|
|
115
|
+
a point client already; changing a client's geometry kind goes through
|
|
116
|
+
`upsert`. Passing the same id list frame after frame is the fast path:
|
|
117
|
+
where each id's row lives is worked out once and reused until a point
|
|
118
|
+
client is added or removed.
|
|
119
|
+
"""
|
|
120
|
+
xy = np.asarray(xy, dtype=float).reshape(-1, 2)
|
|
121
|
+
if len(xy) != len(uids):
|
|
122
|
+
raise ValueError(f"{len(uids)} ids but {len(xy)} coordinates")
|
|
123
|
+
layout = self._layout(uids)
|
|
124
|
+
if layout.others:
|
|
125
|
+
uid = layout.others[0]
|
|
126
|
+
raise KeyError(f"{uid!r} is not a point client" if uid in self._where else uid)
|
|
127
|
+
for store, rows, pos in layout.groups:
|
|
128
|
+
store.write_rows(rows, xy[pos])
|
|
129
|
+
self.generation += 1
|
|
130
|
+
|
|
131
|
+
def remove(self, uids: Iterable[K]) -> None:
|
|
132
|
+
"""Remove clients. Ids the index does not hold are ignored."""
|
|
133
|
+
for uid in uids:
|
|
134
|
+
store = self._where.pop(uid, None)
|
|
135
|
+
if store is None:
|
|
136
|
+
continue
|
|
137
|
+
store.remove(uid)
|
|
138
|
+
if isinstance(store, PointStore):
|
|
139
|
+
self._layout_version += 1
|
|
140
|
+
del self._kind[uid]
|
|
141
|
+
del self._seq[uid]
|
|
142
|
+
self.generation += 1
|
|
143
|
+
|
|
144
|
+
def _upsert_batch(self, items: List[Tuple[K, Optional[Collider]]], kind: Optional[Hashable]):
|
|
145
|
+
"""Parse and validate every collider first, so a refusal leaves the index untouched."""
|
|
146
|
+
parsed = []
|
|
147
|
+
for uid, collider in items:
|
|
148
|
+
if collider is None:
|
|
149
|
+
if self._provider is None:
|
|
150
|
+
raise ValueError(f"no collider given for {uid!r} and no collider_provider to pull one from")
|
|
151
|
+
collider = self._provider(uid)
|
|
152
|
+
parsed.append((uid, parse(collider)))
|
|
153
|
+
validate_shapes([p for _, p in parsed if not isinstance(p, tuple)])
|
|
154
|
+
for uid, p in parsed:
|
|
155
|
+
self._place(uid, p, kind)
|
|
156
|
+
self.generation += 1
|
|
157
|
+
|
|
158
|
+
def _place(self, uid: K, parsed, kind: Optional[Hashable]):
|
|
159
|
+
if kind is None and uid in self._kind:
|
|
160
|
+
kind = self._kind[uid]
|
|
161
|
+
is_point = isinstance(parsed, tuple)
|
|
162
|
+
table = self._points if is_point else self._shapes
|
|
163
|
+
target = table.get(kind)
|
|
164
|
+
if target is None:
|
|
165
|
+
target = table[kind] = PointStore() if is_point else ShapeStore()
|
|
166
|
+
|
|
167
|
+
current = self._where.get(uid)
|
|
168
|
+
if current is not target:
|
|
169
|
+
if current is not None:
|
|
170
|
+
current.remove(uid)
|
|
171
|
+
if isinstance(current, PointStore):
|
|
172
|
+
self._layout_version += 1
|
|
173
|
+
if is_point:
|
|
174
|
+
self._layout_version += 1
|
|
175
|
+
self._where[uid] = target
|
|
176
|
+
if is_point:
|
|
177
|
+
target.put(uid, parsed[0], parsed[1])
|
|
178
|
+
else:
|
|
179
|
+
target.put(uid, parsed)
|
|
180
|
+
|
|
181
|
+
self._kind[uid] = kind
|
|
182
|
+
if uid not in self._seq:
|
|
183
|
+
self._seq[uid] = self._next_seq
|
|
184
|
+
self._next_seq += 1
|
|
185
|
+
|
|
186
|
+
def _layout(self, uids: Sequence[K]) -> _Layout:
|
|
187
|
+
"""Where each id's point row lives, cached for a repeated id list."""
|
|
188
|
+
cached = self._layout_cache
|
|
189
|
+
if cached is not None and cached.version == self._layout_version and cached.uids == uids:
|
|
190
|
+
return cached
|
|
191
|
+
groups: Dict[int, Tuple[PointStore, List[int], List[int]]] = {}
|
|
192
|
+
others: List[K] = []
|
|
193
|
+
point_pos: List[int] = []
|
|
194
|
+
for i, uid in enumerate(uids):
|
|
195
|
+
store = self._where.get(uid)
|
|
196
|
+
if isinstance(store, PointStore):
|
|
197
|
+
group = groups.get(id(store))
|
|
198
|
+
if group is None:
|
|
199
|
+
group = groups[id(store)] = (store, [], [])
|
|
200
|
+
group[1].append(store.row_of(uid))
|
|
201
|
+
group[2].append(i)
|
|
202
|
+
point_pos.append(i)
|
|
203
|
+
else:
|
|
204
|
+
others.append(uid)
|
|
205
|
+
layout = _Layout(
|
|
206
|
+
uids=list(uids),
|
|
207
|
+
version=self._layout_version,
|
|
208
|
+
groups=[(s, np.asarray(rows, dtype=np.intp), np.asarray(pos, dtype=np.intp))
|
|
209
|
+
for s, rows, pos in groups.values()],
|
|
210
|
+
point_pos=np.asarray(point_pos, dtype=np.intp),
|
|
211
|
+
point_ids=[uids[i] for i in point_pos],
|
|
212
|
+
others=others,
|
|
213
|
+
)
|
|
214
|
+
self._layout_cache = layout
|
|
215
|
+
return layout
|
|
216
|
+
|
|
217
|
+
# ── Questions ─────────────────────────────────────────────────────────────
|
|
218
|
+
|
|
219
|
+
def within(self, center: Union[K, Collider], radius: float, kinds: Kinds = None) -> Set[K]:
|
|
220
|
+
"""Clients whose geometry lies within `radius` of `center` (exact distance)."""
|
|
221
|
+
if radius < 0:
|
|
222
|
+
raise ValueError(f"radius must be >= 0, got {radius}")
|
|
223
|
+
geom, exclude = self._resolve(center)
|
|
224
|
+
out: Set[K] = set()
|
|
225
|
+
for store in self._stores(kinds):
|
|
226
|
+
if isinstance(store, PointStore):
|
|
227
|
+
out.update(store.within(geom, radius))
|
|
228
|
+
else:
|
|
229
|
+
out.update(store.query(geom, "dwithin", radius))
|
|
230
|
+
out.discard(exclude)
|
|
231
|
+
return out
|
|
232
|
+
|
|
233
|
+
def intersecting(self, query: Union[K, Collider], kinds: Kinds = None) -> Set[K]:
|
|
234
|
+
"""Clients whose geometry intersects the query's, boundaries included."""
|
|
235
|
+
geom, exclude = self._resolve(query)
|
|
236
|
+
out: Set[K] = set()
|
|
237
|
+
for store in self._stores(kinds):
|
|
238
|
+
if isinstance(store, PointStore):
|
|
239
|
+
out.update(store.intersecting(geom))
|
|
240
|
+
else:
|
|
241
|
+
out.update(store.query(geom, "intersects"))
|
|
242
|
+
out.discard(exclude)
|
|
243
|
+
return out
|
|
244
|
+
|
|
245
|
+
def containing(self, pt: Tuple[float, float], kinds: Kinds = None, tolerance: float = 0.0) -> Set[K]:
|
|
246
|
+
"""
|
|
247
|
+
Clients that cover the point `pt`, or lie within `tolerance` of it.
|
|
248
|
+
|
|
249
|
+
`tolerance` absorbs floating-point gaps where neighbouring polygons
|
|
250
|
+
built from the same vertices do not quite meet.
|
|
251
|
+
"""
|
|
252
|
+
geom = Point(float(pt[0]), float(pt[1]))
|
|
253
|
+
if tolerance > 0:
|
|
254
|
+
return self.within(geom, tolerance, kinds)
|
|
255
|
+
return self.intersecting(geom, kinds)
|
|
256
|
+
|
|
257
|
+
def locate(self, uids: Iterable[K], kinds: Kinds = None, tolerance: float = 0.0) -> Dict[K, Set[K]]:
|
|
258
|
+
"""
|
|
259
|
+
`containing` for many clients at once: {uid: clients it lies in}.
|
|
260
|
+
|
|
261
|
+
Point clients are answered together, in one tree query per store,
|
|
262
|
+
which is what makes "where is every villager" cost one call rather than
|
|
263
|
+
one per villager. A non-point id is answered with `intersecting`.
|
|
264
|
+
"""
|
|
265
|
+
uids = list(uids)
|
|
266
|
+
layout = self._layout(uids)
|
|
267
|
+
out: Dict[K, Set[K]] = {uid: set() for uid in uids}
|
|
268
|
+
for uid in layout.others:
|
|
269
|
+
if uid not in self._where:
|
|
270
|
+
raise KeyError(uid)
|
|
271
|
+
out[uid] = self.within(uid, tolerance, kinds) if tolerance > 0 else self.intersecting(uid, kinds)
|
|
272
|
+
if not layout.point_ids:
|
|
273
|
+
return out
|
|
274
|
+
|
|
275
|
+
xy = np.empty((len(uids), 2), dtype=float)
|
|
276
|
+
for store, rows, pos in layout.groups:
|
|
277
|
+
xy[pos] = store.xy[rows]
|
|
278
|
+
queries = shapely.points(xy[layout.point_pos])
|
|
279
|
+
predicate, distance = ("dwithin", tolerance) if tolerance > 0 else ("intersects", None)
|
|
280
|
+
point_ids = layout.point_ids
|
|
281
|
+
for store in self._stores(kinds):
|
|
282
|
+
qi, matched = store.match(queries, predicate, distance)
|
|
283
|
+
if isinstance(store, PointStore):
|
|
284
|
+
# Only a point store holds the query points themselves.
|
|
285
|
+
for q, other in zip(qi.tolist(), matched):
|
|
286
|
+
if other != point_ids[q]:
|
|
287
|
+
out[point_ids[q]].add(other)
|
|
288
|
+
else:
|
|
289
|
+
for q, other in zip(qi.tolist(), matched):
|
|
290
|
+
out[point_ids[q]].add(other)
|
|
291
|
+
return out
|
|
292
|
+
|
|
293
|
+
def nearest(self, query: Union[K, Collider], k: int = 1, kinds: Kinds = None,
|
|
294
|
+
max_distance: Optional[float] = None) -> List[Tuple[K, float]]:
|
|
295
|
+
"""
|
|
296
|
+
Up to `k` clients closest to the query as (id, distance), nearest first.
|
|
297
|
+
|
|
298
|
+
Ties break by the order clients were first added. Fewer than `k` come
|
|
299
|
+
back when fewer exist (or lie within `max_distance`).
|
|
300
|
+
"""
|
|
301
|
+
if k < 1:
|
|
302
|
+
raise ValueError(f"k must be >= 1, got {k}")
|
|
303
|
+
geom, exclude = self._resolve(query)
|
|
304
|
+
candidates: List[Tuple[K, float]] = []
|
|
305
|
+
for store in self._stores(kinds):
|
|
306
|
+
need = k + (1 if exclude in store else 0)
|
|
307
|
+
if isinstance(store, PointStore):
|
|
308
|
+
if not len(store):
|
|
309
|
+
continue
|
|
310
|
+
d = store.distances(geom)
|
|
311
|
+
if max_distance is not None:
|
|
312
|
+
keep = np.flatnonzero(d <= max_distance)
|
|
313
|
+
else:
|
|
314
|
+
keep = np.arange(len(d))
|
|
315
|
+
if len(keep) > need:
|
|
316
|
+
keep = keep[np.argpartition(d[keep], need - 1)[:need]]
|
|
317
|
+
candidates.extend((store.ids[i], float(d[i])) for i in keep)
|
|
318
|
+
else:
|
|
319
|
+
candidates.extend(store.nearest(geom, need, max_distance))
|
|
320
|
+
candidates = [(uid, d) for uid, d in candidates
|
|
321
|
+
if uid != exclude and (max_distance is None or d <= max_distance)]
|
|
322
|
+
candidates.sort(key=lambda c: (c[1], self._seq[c[0]]))
|
|
323
|
+
return candidates[:k]
|
|
324
|
+
|
|
325
|
+
def pairs(self, kinds_a: Kinds = None, kinds_b: Kinds = None) -> Iterator[Tuple[K, K]]:
|
|
326
|
+
"""
|
|
327
|
+
Every intersecting (a, b) with a's kind in `kinds_a` and b's in `kinds_b`.
|
|
328
|
+
|
|
329
|
+
A pair that qualifies in both orders is yielded once, earliest-added
|
|
330
|
+
client first.
|
|
331
|
+
"""
|
|
332
|
+
want_a, want_b = self._kind_set(kinds_a), self._kind_set(kinds_b)
|
|
333
|
+
side_a = self.ids(kinds_a)
|
|
334
|
+
if not side_a:
|
|
335
|
+
return
|
|
336
|
+
queries = np.array([self.geometry(uid) for uid in side_a], dtype=object)
|
|
337
|
+
seen: Set[Tuple[K, K]] = set()
|
|
338
|
+
for store in self._stores(kinds_b):
|
|
339
|
+
qi, matched = store.match(queries, "intersects", None)
|
|
340
|
+
for q, b in zip(qi, matched):
|
|
341
|
+
a = side_a[q]
|
|
342
|
+
if a == b:
|
|
343
|
+
continue
|
|
344
|
+
a_is_b_side = want_b is None or self._kind[a] in want_b
|
|
345
|
+
b_is_a_side = want_a is None or self._kind[b] in want_a
|
|
346
|
+
if a_is_b_side and b_is_a_side:
|
|
347
|
+
pair = (a, b) if self._seq[a] < self._seq[b] else (b, a)
|
|
348
|
+
else:
|
|
349
|
+
pair = (a, b)
|
|
350
|
+
if pair not in seen:
|
|
351
|
+
seen.add(pair)
|
|
352
|
+
yield pair
|
|
353
|
+
|
|
354
|
+
# ── Introspection ─────────────────────────────────────────────────────────
|
|
355
|
+
|
|
356
|
+
def geometry(self, uid: K) -> BaseGeometry:
|
|
357
|
+
store = self._where[uid]
|
|
358
|
+
if isinstance(store, PointStore):
|
|
359
|
+
return Point(store.point(uid))
|
|
360
|
+
return store.geometry(uid)
|
|
361
|
+
|
|
362
|
+
def point(self, uid: K) -> Tuple[float, float]:
|
|
363
|
+
store = self._where[uid]
|
|
364
|
+
if not isinstance(store, PointStore):
|
|
365
|
+
raise KeyError(f"{uid!r} is not a point client")
|
|
366
|
+
return store.point(uid)
|
|
367
|
+
|
|
368
|
+
def kind_of(self, uid: K) -> Hashable:
|
|
369
|
+
return self._kind[uid]
|
|
370
|
+
|
|
371
|
+
def bounds(self, uid: K) -> Bounds:
|
|
372
|
+
store = self._where[uid]
|
|
373
|
+
if isinstance(store, PointStore):
|
|
374
|
+
x, y = store.point(uid)
|
|
375
|
+
return x, y, x, y
|
|
376
|
+
return tuple(float(v) for v in store.geometry(uid).bounds)
|
|
377
|
+
|
|
378
|
+
def ids(self, kinds: Kinds = None) -> List[K]:
|
|
379
|
+
"""Client ids in the order they were first added."""
|
|
380
|
+
wanted = self._kind_set(kinds)
|
|
381
|
+
return [uid for uid, kind in self._kind.items() if wanted is None or kind in wanted]
|
|
382
|
+
|
|
383
|
+
def stats(self) -> SpatialIndexStats:
|
|
384
|
+
kinds = {}
|
|
385
|
+
for kind in set(self._points) | set(self._shapes):
|
|
386
|
+
p, s = self._points.get(kind), self._shapes.get(kind)
|
|
387
|
+
kinds[kind] = KindStats(points=len(p) if p else 0,
|
|
388
|
+
shapes=len(s) if s else 0,
|
|
389
|
+
tree_rebuilds=s.rebuilds if s else 0)
|
|
390
|
+
return SpatialIndexStats(clients=len(self._kind), generation=self.generation, kinds=kinds)
|
|
391
|
+
|
|
392
|
+
def __len__(self) -> int:
|
|
393
|
+
return len(self._kind)
|
|
394
|
+
|
|
395
|
+
def __contains__(self, uid) -> bool:
|
|
396
|
+
try:
|
|
397
|
+
return uid in self._kind
|
|
398
|
+
except TypeError:
|
|
399
|
+
return False
|
|
400
|
+
|
|
401
|
+
# ── Internals ─────────────────────────────────────────────────────────────
|
|
402
|
+
|
|
403
|
+
def _resolve(self, query) -> Tuple[BaseGeometry, object]:
|
|
404
|
+
"""A query's geometry, plus the client id to leave out of the answer."""
|
|
405
|
+
if not isinstance(query, BaseGeometry) and query in self:
|
|
406
|
+
return self.geometry(query), query
|
|
407
|
+
return to_geometry(query), _NOBODY
|
|
408
|
+
|
|
409
|
+
@staticmethod
|
|
410
|
+
def _kind_set(kinds: Kinds) -> Optional[Set[Hashable]]:
|
|
411
|
+
if kinds is None:
|
|
412
|
+
return None
|
|
413
|
+
if isinstance(kinds, (str, bytes)) or not isinstance(kinds, Iterable):
|
|
414
|
+
return {kinds}
|
|
415
|
+
return set(kinds)
|
|
416
|
+
|
|
417
|
+
def _stores(self, kinds: Kinds) -> List[Store]:
|
|
418
|
+
wanted = self._kind_set(kinds)
|
|
419
|
+
out: List[Store] = []
|
|
420
|
+
for table in (self._points, self._shapes):
|
|
421
|
+
for kind, store in table.items():
|
|
422
|
+
if len(store) and (wanted is None or kind in wanted):
|
|
423
|
+
out.append(store)
|
|
424
|
+
return out
|