Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up pathfinding by introducing Cython #123

Merged
merged 167 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
167 commits
Select commit Hold shift + click to select a range
a12b93f
Add Cython to requirements
CyberiaResurrection Aug 15, 2024
22b1f4a
Add inital Cython setup.py
CyberiaResurrection Aug 15, 2024
d7d019b
Initialise zero values as floats
CyberiaResurrection Aug 17, 2024
2bfeadf
Change source's parent node to -1
CyberiaResurrection Aug 17, 2024
5b63a0a
Hoist out neighbour retrieval
CyberiaResurrection Aug 18, 2024
ca5565c
Type more get_neighbours vars
CyberiaResurrection Aug 18, 2024
125128c
Hoist get_neighbours out of astar_numpy
CyberiaResurrection Aug 18, 2024
737d5db
Move nodes push-to-queue to astar_numpy_core
CyberiaResurrection Aug 18, 2024
bf0e39d
Type vars in push_to_queue
CyberiaResurrection Aug 18, 2024
edc0fc0
Memoise len(G) calls
CyberiaResurrection Aug 18, 2024
d39b06d
Type more vars in push_to_queue
CyberiaResurrection Aug 18, 2024
e2fd588
Type more vars in get_neighbours
CyberiaResurrection Aug 18, 2024
cac4663
Lowercase g_succ in astar_get_neighbours
CyberiaResurrection Aug 19, 2024
3bbdc1a
Type parms to astar_push_to_queue
CyberiaResurrection Aug 19, 2024
cc603c3
Simplify push_to_queue
CyberiaResurrection Aug 19, 2024
ed261f0
Fix arg typing for push_to_queue
CyberiaResurrection Aug 19, 2024
08ed68d
Relax checks for push_to_queue
CyberiaResurrection Aug 19, 2024
1181ddb
Relax checks for get_neighbours
CyberiaResurrection Aug 19, 2024
1383a3b
Hoist dijkstra_core out to its own file
CyberiaResurrection Aug 19, 2024
3c15c85
Relax checks for dijkstra_core
CyberiaResurrection Aug 19, 2024
bca72ce
Fix arg typing of dijkstra_core
CyberiaResurrection Aug 19, 2024
830a348
Type most internal vars of dijkstra_core
CyberiaResurrection Aug 19, 2024
b58d3bc
Type last arg of dijkstra_core
CyberiaResurrection Aug 19, 2024
933a188
Type most internal vars of dijkstra_core
CyberiaResurrection Aug 19, 2024
70d86a0
Inline floatinf check in explicit_SP_dijkstra
CyberiaResurrection Aug 19, 2024
2d83851
Make loop indices size_t
CyberiaResurrection Aug 19, 2024
9e2cae9
Unpack distance-label update in dijkstra_core
CyberiaResurrection Aug 19, 2024
e1ea438
Try first cut at typed memoryview
CyberiaResurrection Aug 19, 2024
edbf190
Try second cut at typed memoryview
CyberiaResurrection Aug 19, 2024
3b6bf84
Try two memoryviews at once
CyberiaResurrection Aug 19, 2024
f21034b
Finally type tail and dist_tail
CyberiaResurrection Aug 19, 2024
6093136
Place memoryview over parents in dijkstra_core
CyberiaResurrection Aug 19, 2024
de23c98
Inline active_weights calc in dijkstra_core
CyberiaResurrection Aug 19, 2024
193d903
Fix arg type in dijkstra core
CyberiaResurrection Aug 19, 2024
1d47dc2
Add diagnostic log messages to TradeCalculation
CyberiaResurrection Aug 20, 2024
d6e15fc
Unpack distance-busting node removal
CyberiaResurrection Aug 20, 2024
fc1c7e1
Remove direct active_costs reference
CyberiaResurrection Aug 20, 2024
6505fae
Inline astar_push_to_queue
CyberiaResurrection Aug 20, 2024
5031428
Empty-guard dijkstra neighbour processing
CyberiaResurrection Aug 20, 2024
b89fb27
Prep neighbour-handling part of astar_numpy for cythonisation
CyberiaResurrection Aug 20, 2024
6203609
Hoist astar_process_neighbours to astar_numpy_core
CyberiaResurrection Aug 20, 2024
9afc83f
Rework target-select portion of astar_process_neighbours
CyberiaResurrection Aug 20, 2024
4409700
Unroll distances-update part of astar_process_neighbours
CyberiaResurrection Aug 20, 2024
6185a13
Repoint distances updates in astar_process_neighbours
CyberiaResurrection Aug 20, 2024
8aa447b
Type int parms of astar_process_neighbours
CyberiaResurrection Aug 20, 2024
397d943
Type float parms of astar_process_neighbours
CyberiaResurrection Aug 20, 2024
e8233b5
Type float-array parms of astar_process_neighbours
CyberiaResurrection Aug 20, 2024
7909f98
Type queue parm in astar_process_neighbours
CyberiaResurrection Aug 20, 2024
32d84ce
Misc fixen in astar_process_neighbours
CyberiaResurrection Aug 20, 2024
32b574d
Roll up exhausted-neighbours check in astar_process_neighbours
CyberiaResurrection Aug 20, 2024
e48cb5c
Misc fixen in astar_process_neighbours
CyberiaResurrection Aug 20, 2024
b8c2e14
Inline new upbound value
CyberiaResurrection Aug 21, 2024
7e932ff
Give astar_numpy single point of exit
CyberiaResurrection Aug 21, 2024
8dd5a15
Re-inline astar_get_neighbours
CyberiaResurrection Aug 21, 2024
e5f7ea7
Re-inline astar_process_neighbours
CyberiaResurrection Aug 21, 2024
5d48a4d
Fold initial upper_limit processing in
CyberiaResurrection Aug 21, 2024
1335839
Extract astar_numpy_core
CyberiaResurrection Aug 21, 2024
27d8291
Inline bestpath in astar_numpy_core
CyberiaResurrection Aug 21, 2024
0904b61
Type diagnostic counters in astar_numpy_core
CyberiaResurrection Aug 21, 2024
0405da4
Add upper_limit_view in astar_numpy_core
CyberiaResurrection Aug 21, 2024
c25e54f
Infer cython types in astar_numpy_core
CyberiaResurrection Aug 21, 2024
58cde45
Add distances_view in astar_numpy_core
CyberiaResurrection Aug 21, 2024
1b95c1a
Move queue init into astar_numpy_core
CyberiaResurrection Aug 21, 2024
557bba8
Type source and target parms of astar_numpy_core
CyberiaResurrection Aug 21, 2024
af22570
Relax bunch of unneeded checks in astar_numpy_core
CyberiaResurrection Aug 21, 2024
2b842eb
Turn ApproximateShortestPathForestUnified into extension class
CyberiaResurrection Aug 22, 2024
77c9126
Ease checks in lower_bound_bulk
CyberiaResurrection Aug 22, 2024
eaa35d5
Fix name collision in _get_sources()
CyberiaResurrection Aug 22, 2024
0faa75d
Type args to lower_bound_bulk
CyberiaResurrection Aug 23, 2024
f2c7cdb
Type internal vars of lower_bound_bulk
CyberiaResurrection Aug 23, 2024
d17d22f
Type vars and args of _mona_lisa_overdrive
CyberiaResurrection Aug 23, 2024
676df16
Type return value of lower_bound_bulk
CyberiaResurrection Aug 23, 2024
f07c805
Change distance heuristic
CyberiaResurrection Aug 23, 2024
307b6e5
Relax checks for update_edges
CyberiaResurrection Aug 23, 2024
54efc4c
Unpack shelf-weight retrieval in update_edges
CyberiaResurrection Aug 23, 2024
5be796a
Type more vars in update_edges
CyberiaResurrection Aug 24, 2024
a67654b
Don't groom queue on new upper bound
CyberiaResurrection Aug 24, 2024
baab9f3
Update readme.md to note compilation needed
CyberiaResurrection Aug 24, 2024
71b7ff9
Type G_succ arg in astar_numpy_core
CyberiaResurrection Aug 24, 2024
aaf1ed1
Type rest of astar_numpy_core args
CyberiaResurrection Aug 24, 2024
38f661b
Init min_cost and dist_view source/target in astar_numpy_core
CyberiaResurrection Aug 24, 2024
3b1ffd7
Move explored declaration to astar_numpy_core
CyberiaResurrection Aug 24, 2024
2481250
Type _calc_branching_factor
CyberiaResurrection Aug 25, 2024
d2f775f
Unify np.abs calls in lower_bound_bulk
CyberiaResurrection Aug 26, 2024
301032a
Split out neighbour filtering
CyberiaResurrection Aug 26, 2024
038f594
Process augmented weights one at a time
CyberiaResurrection Aug 26, 2024
4bbdd0a
Use potentials view when processing aug weights
CyberiaResurrection Aug 26, 2024
a643317
Cache whether any mona lisa overdrive results are true
CyberiaResurrection Aug 26, 2024
b11b4b6
Type triangle_upbound parms and vars
CyberiaResurrection Aug 26, 2024
fb77499
Unwrap maxdelta determination in update_edges
CyberiaResurrection Aug 26, 2024
c99e34a
Lighten setup iterator in update_edges
CyberiaResurrection Aug 26, 2024
56be6f1
Fix shelf typing in update_edges
CyberiaResurrection Aug 26, 2024
69d19c8
Remove specialisation option for lower_bound_bulk
CyberiaResurrection Aug 26, 2024
4ab4a3f
Fix test blast damage
CyberiaResurrection Aug 26, 2024
d7174be
Filter bound-bust neighbours on upper limit, not distances
CyberiaResurrection Aug 27, 2024
f3af194
Make mona_lisa_overdrive a C-only function
CyberiaResurrection Aug 27, 2024
f4f9c76
Use explicit-dijkstra when updating edges
CyberiaResurrection Aug 27, 2024
3ecb04e
Cythonise astar_numpy
CyberiaResurrection Aug 27, 2024
7ac2c8d
Type vars in astar_path_numpy
CyberiaResurrection Aug 27, 2024
cfbfb52
Default upbound to max float value in astar_numpy
CyberiaResurrection Aug 27, 2024
deb7b97
Remove specialisation option for min_cost
CyberiaResurrection Aug 28, 2024
b402d8e
Relax checks in astar_path_numpy
CyberiaResurrection Aug 28, 2024
fb6fe6d
Drop superfluous infinite-upbound checks
CyberiaResurrection Aug 28, 2024
e5a5bb5
Add return types to astar_numpy
CyberiaResurrection Aug 28, 2024
4660d09
Fold dijkstra heap init into dijkstra_core
CyberiaResurrection Aug 31, 2024
c712909
Add first cut at minmaxheap
CyberiaResurrection Aug 31, 2024
5e28e75
Update gitignore
CyberiaResurrection Aug 31, 2024
8c62bbf
Hook minmaxheap up to single_source_dijkstra_core
CyberiaResurrection Aug 31, 2024
49b2638
Move parents init to single_source_dijkstra_core
CyberiaResurrection Aug 31, 2024
0039b55
Hook minmaxheap up to astar_numpy_core
CyberiaResurrection Aug 31, 2024
6091f5b
Add returns annotation to lower_bound_bulk
CyberiaResurrection Aug 31, 2024
09a8d6a
Seed astar distances with upper bound
CyberiaResurrection Aug 31, 2024
ad6ee59
Move active_weights prune after empty active_nodes check
CyberiaResurrection Aug 31, 2024
938712d
Drop redundant assertion
CyberiaResurrection Sep 1, 2024
13a90ef
Drop min_cost input to astar_path_numpy
CyberiaResurrection Sep 2, 2024
a75fb51
Don't round off upbound
CyberiaResurrection Sep 2, 2024
73b0dab
Pull landsmarks back to 3x log (size)
CyberiaResurrection Sep 2, 2024
3eee6e3
Don't add historic costs to existing edges
CyberiaResurrection Sep 2, 2024
a9747d6
Simplify node neighbour processing
CyberiaResurrection Sep 2, 2024
db90cd7
Shut up, ruff!
CyberiaResurrection Sep 3, 2024
3572d59
Add cython build to CI job
CyberiaResurrection Sep 3, 2024
30d1815
Add first node to existing path, don't create new one
CyberiaResurrection Sep 3, 2024
c85160f
Inline raw_nodes
CyberiaResurrection Sep 3, 2024
4a2dfd0
Drop unused DistanceGraph._min_mask
CyberiaResurrection Sep 4, 2024
b0aa2c5
Re-arrange DistanceGraph ctor
CyberiaResurrection Sep 4, 2024
bfec31c
Drop unused Galaxy.landmarks
CyberiaResurrection Sep 4, 2024
6c29931
Bump min historic route length to 6
CyberiaResurrection Sep 4, 2024
74b8b78
Define __slots__ on DistanceGraph
CyberiaResurrection Sep 4, 2024
b3a906e
Add intermediate landmark signpost
CyberiaResurrection Sep 4, 2024
8b73fa1
Characterise zero-arg in landmarks transpose
CyberiaResurrection Sep 5, 2024
dd4ed5e
Fix zero-arg in landmarks transpose
CyberiaResurrection Sep 5, 2024
17e7856
Fix too-small-wtn star filtering
CyberiaResurrection Sep 6, 2024
4a40fbe
Fix test blast damage
CyberiaResurrection Sep 7, 2024
50abf75
Actually type distances array
CyberiaResurrection Sep 7, 2024
25f32fb
Actually return dict from astar_numpy
CyberiaResurrection Sep 8, 2024
80a12f2
Only get route cost when adding historic route
CyberiaResurrection Sep 8, 2024
e7d6696
Memoise RouteLandmarkGraph._check_index
CyberiaResurrection Sep 8, 2024
15d1143
Require indexes in TradeCalculation._preheat_upper_bound
CyberiaResurrection Sep 8, 2024
e3bbada
Drop extra upbound cases
CyberiaResurrection Sep 8, 2024
b597fc2
Drop superfluous min call
CyberiaResurrection Sep 8, 2024
a23e325
Memoise AllyGen.same_align
CyberiaResurrection Sep 8, 2024
c353935
Convert cross_check_totals to use comprehensions
CyberiaResurrection Sep 8, 2024
551c7f8
Inline exhausted check
CyberiaResurrection Sep 8, 2024
695db8a
Hoist out passed-over stars to their own loop
CyberiaResurrection Sep 8, 2024
0df6bc3
Fix TradeMPCalculation blast damage
CyberiaResurrection Sep 8, 2024
892afce
Inline len_G call
CyberiaResurrection Sep 9, 2024
318ee60
Inline upbound default value
CyberiaResurrection Sep 9, 2024
b7bf136
Make compiled code cProfile-able
CyberiaResurrection Sep 9, 2024
08dd5c4
Align approxSP._distances memory layout with access
CyberiaResurrection Sep 9, 2024
be7394d
Memoise Star hex position
CyberiaResurrection Sep 10, 2024
8200864
Inline dq/dr in Hex.axial_distance
CyberiaResurrection Sep 10, 2024
1938552
Pull landmarks back to 2x log size
CyberiaResurrection Sep 10, 2024
0eb6c2c
Add back-end support instructions to README
CyberiaResurrection Sep 11, 2024
961ed6e
Pass optional distance to TradeCalculation.route_update_simple
CyberiaResurrection Sep 11, 2024
67bafb9
Collapse upbound-preheat cases
CyberiaResurrection Sep 11, 2024
0c5d0a6
Move active-label retrieval after empty adjacent check
CyberiaResurrection Sep 11, 2024
85c1c0c
Update astar_numpy blurb
CyberiaResurrection Sep 12, 2024
019f5ab
Explicitly dtype distances and max_labels
CyberiaResurrection Sep 14, 2024
120fb48
Don't annotate builds
CyberiaResurrection Sep 14, 2024
d6250bf
Add non-cython fallbacks
CyberiaResurrection Sep 15, 2024
75d7438
Characterise non-cython astar diagnostics
CyberiaResurrection Sep 15, 2024
af328f6
Update README instructions
CyberiaResurrection Sep 22, 2024
f5174a8
Update PDF gen in readme
CyberiaResurrection Sep 26, 2024
8e21c03
Check sophont dieback alongside active populations
CyberiaResurrection Sep 28, 2024
5fe33b4
Update sector list
CyberiaResurrection Sep 29, 2024
498c579
Include allegiance name in error messages
CyberiaResurrection Sep 29, 2024
ce15bf4
Verify Aslan allegiances are properly handled
CyberiaResurrection Sep 29, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ jobs:
run: |
# now run configured options
ruff check --preview PyRoute
- name: Run non-cython tests
run: |
pytest -k testAstarOverSubsector
- name: Set up cython build
run: |
cd $LD_LIBRARY_PATH/python3.9/site-packages/numpy/
ls -al
cp __init__.cython-30.pxd numpy.pxd
- name: Build cython modules
run: |
cd PyRoute/Pathfinding
python3 setup.py build_ext --inplace
- name: Test with pytest
run: |
pytest
Expand Down
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,8 @@ venv2/
sectors/
maps/
diffs/
test_data/
test_data/
PyRoute/Pathfinding/*.c
PyRoute/Pathfinding/*.cpp
PyRoute/Pathfinding/*.cpython*
PyRoute/Pathfinding/*.html
1 change: 1 addition & 0 deletions PyRoute/AllyGen.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ def is_client_state(alg):
return alg.code[0:2] == 'Cs'

@staticmethod
@functools.cache
def same_align(alg):
for sameAlg in AllyGen.sameAligned:
if alg in sameAlg:
Expand Down
12 changes: 6 additions & 6 deletions PyRoute/AreaItems/Allegiance.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@ def allegiance_name(name, code, base):
name = name.strip()
if '' == name:
raise ValueError("Name must not be empty string")
if code.startswith('As'):
if code.startswith('As') or "As" == AllyGen.same_align(code):
if 5 < name.count(','):
raise ValueError("Name must have at most five commas")
raise ValueError("Name " + name + ", must have at most five commas")
else:
if 1 < name.count(','):
raise ValueError("Name must have at most one comma")
raise ValueError("Name " + name + ", must have at most one comma")
namelen = 0
while namelen != len(name):
namelen = len(name)
Expand Down Expand Up @@ -78,7 +78,7 @@ def set_wiki_name(name, code, base):
if ',' == name:
raise ValueError("Name must not be pair of empty strings")
if '[' in name or ']' in name:
raise ValueError("Name must not contain square brackets")
raise ValueError("Name must not contain square brackets - received " + name)

names = name.split(',') if ',' in name else [name, '']
names[0] = names[0].strip()
Expand Down Expand Up @@ -120,10 +120,10 @@ def is_well_formed(self):
msg = "Allegiance name should not be empty"
return False, msg
if ' ' in self.name:
msg = "Should not have successive spaces in allegiance name"
msg = "Should not have successive spaces in allegiance name, " + self.name
return False, msg
if 1 < self.name.count(','):
msg = "Should be at most one comma in allegiance name"
msg = "Should be at most one comma in allegiance name, " + self.name
return False, msg

return True, msg
10 changes: 5 additions & 5 deletions PyRoute/AreaItems/Galaxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ def __init__(self, min_btn, max_jump=4):
self.output_path = 'maps'
self.max_jump_range = max_jump
self.min_btn = min_btn
self.landmarks = dict()
self.historic_costs = None
self.big_component = None
self.star_mapping = dict()
Expand All @@ -68,7 +67,7 @@ def __getstate__(self):
# def read_sectors(self, sectors, pop_code, ru_calc,
# route_reuse, trade_choice, route_btn, mp_threads, debug_flag, fix_pop=False):
def read_sectors(self, options):
assert isinstance(options, ReadSectorOptions)
assert isinstance(options, ReadSectorOptions), "options parm not ReadSectorOptions, is " + type(options).__name__
route_reuse = options.route_reuse
trade_choice = options.trade_choice
route_btn = options.route_btn
Expand Down Expand Up @@ -170,7 +169,7 @@ def add_star_to_galaxy(self, star: Star, star_counter: int, sec: Sector):
star.is_well_formed()
return star_counter + 1

def set_area_alg(self, star, area, algs):
def set_area_alg(self, star, area, algs: dict):
full_alg = algs.get(star.alg_code, Allegiance(star.alg_code, 'Unknown Allegiance', base=False))
base_alg = algs.get(star.alg_base_code, Allegiance(star.alg_base_code, 'Unknown Allegiance', base=True))

Expand Down Expand Up @@ -393,8 +392,9 @@ def is_well_formed(self):
star = self.star_mapping[item]
star.is_well_formed()

def heuristic_distance_bulk(self, active_nodes, target):
raw = self.trade.shortest_path_tree.lower_bound_bulk(active_nodes, target)
def heuristic_distance_bulk(self, target):
active_nodes = self.stars.nodes.values()
raw = self.trade.shortest_path_tree.lower_bound_bulk(target)
distances = self.trade.star_graph.distances_from_target(active_nodes, target)
# Case-wise maximum of 2 or more admissible heuristics (approx-SP bound, existing route distances) is itself
# admissible
Expand Down
21 changes: 14 additions & 7 deletions PyRoute/Calculation/CommCalculation.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,22 @@

@author: CyberiaResurrection
"""
import copy

import networkx as nx

from PyRoute.AllyGen import AllyGen
from PyRoute.Calculation.RouteCalculation import RouteCalculation
from PyRoute.Pathfinding.ApproximateShortestPathForestUnified import ApproximateShortestPathForestUnified
from PyRoute.Pathfinding.astar_numpy import astar_path_numpy
try:
from PyRoute.Pathfinding.ApproximateShortestPathForestUnified import ApproximateShortestPathForestUnified
except ModuleNotFoundError:
from PyRoute.Pathfinding.ApproximateShortestPathForestUnifiedFallback import ApproximateShortestPathForestUnified
except ImportError:
from PyRoute.Pathfinding.ApproximateShortestPathForestUnifiedFallback import ApproximateShortestPathForestUnified
try:
from PyRoute.Pathfinding.astar_numpy import astar_path_numpy
except ModuleNotFoundError:
from PyRoute.Pathfinding.astar_numpy_fallback import astar_path_numpy
except ImportError:
from PyRoute.Pathfinding.astar_numpy_fallback import astar_path_numpy


class CommCalculation(RouteCalculation):
Expand Down Expand Up @@ -201,10 +209,9 @@ def lesser_importance(self, star, neighbor):

def get_route_between(self, star, target):
try:
mincost = copy.deepcopy(self.star_graph._min_cost)
upbound = self.shortest_path_tree.triangle_upbound(star, target) * 1.005
upbound = self.shortest_path_tree.triangle_upbound(star.index, target.index) * 1.005
route, _ = astar_path_numpy(self.star_graph, star.index, target.index,
self.galaxy.heuristic_distance_bulk, min_cost=mincost, upbound=upbound)
self.galaxy.heuristic_distance_bulk, upbound=upbound)
except nx.NetworkXNoPath:
return

Expand Down
Loading