-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctionTopology.py
More file actions
1638 lines (1337 loc) · 60.7 KB
/
FunctionTopology.py
File metadata and controls
1638 lines (1337 loc) · 60.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import random
from time import time
from collections import defaultdict
# Math
import numpy as np
from scipy.spatial import Delaunay, KDTree
# Network algorithms
import networkx
from networkx.algorithms.tree.mst import maximum_spanning_tree, minimum_spanning_tree
from networkx.algorithms.shortest_paths.generic import shortest_path
from networkx.algorithms.components.connected import connected_components
# Imports for typing only
from typing import Tuple, List, Dict, Iterator, Sequence, Set, Optional
# Import topology input section object for typing and to copy default values from
from topgrid.TopologyInput import TopologyInput, GraphSteepestAscentMethod
from topgrid.TopologyPlot import TopologyPlot
class FunctionTopology:
def __init__(self,
points: Sequence[Sequence[float]],
function: Sequence[float],
gradients: Sequence[float] = None,
settings: TopologyInput = None):
"""
Create a function topology for the given
function defined on the given set of points.
Parameters
----------
points: Sequence[Sequence[float]]
Points in R^N at which the function is defined; points[i] should return the i^th point.
function: Sequence[float]
For each point, the value of the function at that point.
"""
# Will contain already-calculated things for retrieval
self._stored_properties = dict()
self._analytic_gradients = None if gradients is None else np.array(gradients)
# Convert points/function to numpy arrays and assert they are compatible shapes
self.points: np.ndarray = np.array(points)
self.function: np.ndarray = np.array(function)
assert len(self.function.shape) == 1
assert len(self.points.shape) == 2
assert self.points.shape[0] == self.function.shape[0]
if self._analytic_gradients is not None:
assert self._analytic_gradients.shape == self.points.shape
# Use default settings if no settings provided
self.settings = settings or TopologyInput()
##############
# PROPERTIES #
##############
@property
def points(self) -> np.ndarray:
"""
The points at which the function whose
topology we are analysing is evaluated.
"""
return self._points
@points.setter
def points(self, val: np.ndarray):
self._points = val
self.clear_stored_properties() # Points changed => we need to re-evaluate things
@property
def function(self) -> np.ndarray:
"""
The function whose topology we're analysing.
"""
return self._function
@function.setter
def function(self, func: np.ndarray):
self._function = np.array(func)
self.min_function = min(func)
self.max_function = max(func)
self.clear_stored_properties() # Function changed => we need to re-evaluate things
@property
def print_method(self) -> callable:
return TimeAndStore.print_method
@print_method.setter
def print_method(self, value):
TimeAndStore.print_method = value
@property
def stored_properties_count(self):
return len(self._stored_properties)
def clear_stored_properties(self):
self._stored_properties.clear()
########################
# READ-ONLY PROPERTIES #
########################
@property
def dimensions(self) -> int:
return self.points.shape[1]
@property
def triangulation(self) -> Delaunay:
with TimeAndStore(self._stored_properties, "Evaluating triangulation") as stored:
if stored.value is not None:
return stored.value
self.print(f"Evaluating topology of function in range "
f"[{self.min_function:.3}, {self.max_function:.3}] "
f"defined on {len(self.points)} points...")
stored.value = Delaunay(self.points, incremental=False)
return stored.value
@property
def graph(self) -> networkx.Graph:
"""
A graph over input points, with edges connecting neighbouring points.
"""
with TimeAndStore(self._stored_properties, "Constructing graph") as stored:
if stored.value is not None:
return stored.value
if self.dimensions == 1:
graph = networkx.Graph()
indices = list(range(len(self.points)))
indices.sort(key=lambda i: self.points[i][0])
graph.add_edges_from((indices[n - 1], indices[n]) for n in range(1, len(indices)))
stored.value = graph
return graph
if self.settings.nearest_neighbour_graph is not None:
graph = networkx.Graph()
for i in range(len(self.points)):
dists, index = self.kd_tree.query(self.points[i], k=self.settings.nearest_neighbour_graph + 1)
for j in index:
if i != j:
graph.add_edge(i, j)
stored.value = graph
return graph
# All vertices from the same simplex, or coplanar vertices are edges on the graph
graph = networkx.Graph()
graph.add_edges_from((i, j) for simplex in self.triangulation.simplices
for i in simplex for j in simplex if i < j)
graph.add_edges_from((i, j) for i, facet, j in self.triangulation.coplanar)
stored.value = graph
return graph
@property
def gradient(self) -> np.ndarray:
"""
The gradient at each point, such that gradient[i] is a d-dimensional vector.
"""
with TimeAndStore(self._stored_properties, "Evaluating gradients") as stored:
if stored.value is not None:
return stored.value
if self._analytic_gradients is not None:
# Use analytic gradients if they are provided
stored.value = self._analytic_gradients
return stored.value
else:
# Fallback to numerical gradients
stored.value = self.numerical_gradients
return stored.value
@property
def numerical_gradients(self) -> np.ndarray:
with TimeAndStore(self._stored_properties, "Evaluating numerical gradients") as stored:
if stored.value is not None:
return stored.value
def min_residual_gradient(i):
deltas = [self.points[n] - self.points[i] for n in self.graph[i]]
delta_functions = [self.function[n] - self.function[i] for n in self.graph[i]]
matrix = sum(np.outer(d, d) for d in deltas)
vector = sum(d * fd for d, fd in zip(deltas, delta_functions))
return np.linalg.inv(matrix) @ vector
stored.value = [min_residual_gradient(i) for i in range(len(self.points))]
return stored.value
@property
def kd_tree(self) -> KDTree:
"""
The KD Tree of my points.
"""
with TimeAndStore(self._stored_properties, "Evaluating KD tree") as stored:
if stored.value is not None:
return stored.value
stored.value = KDTree(self.points)
return stored.value
@property
def average_function_edge_attributes_set(self) -> bool:
with TimeAndStore(self._stored_properties, "Setting average function edge attributes") as stored:
if stored.value is not None:
return stored.value
networkx.set_edge_attributes(
self.graph,
{tuple(e): (self.function[e[0]] + self.function[e[1]]) / 2.0 for e in self.graph.edges},
"average function value")
stored.value = True
return True
@property
def abs_gradient_edge_attributes_set(self) -> bool:
with TimeAndStore(self._stored_properties, "Setting absolute gradient edge attributes") as stored:
if stored.value is not None:
return stored.value
def abs_gradient(e):
delta = self.function[e[0]] - self.function[e[1]]
delta /= np.linalg.norm(self.points[e[0]] - self.points[e[1]])
return abs(delta)
networkx.set_edge_attributes(
self.graph,
{tuple(e): abs_gradient(e) for e in self.graph.edges},
"abs gradient")
stored.value = True
return True
@property
def convex_hull(self) -> Set[int]:
with TimeAndStore(self._stored_properties, "Evaluating convex hull") as stored:
if stored.value is not None:
return stored.value
if self.dimensions == 1:
hull = set()
hull.add(max(range(len(self.points)), key=lambda i: self.points[i][0]))
hull.add(min(range(len(self.points)), key=lambda i: self.points[i][0]))
stored.value = hull
return hull
hull = set()
for face in self.triangulation.convex_hull:
for index in face:
hull.add(index)
for i in range(self.settings.convex_hull_depth - 1):
new_hull = set(hull)
for index in hull:
for neighbour in self.graph[index]:
new_hull.add(neighbour)
hull = new_hull
stored.value = hull
return hull
@property
def climb_graph(self) -> networkx.DiGraph:
"""
A directed spanning tree over the whole network that describes
the path from any given point to it's associated maximum.
"""
with TimeAndStore(self._stored_properties, "Evaluating climb graph") as stored:
if stored.value is not None:
return stored.value
climb_graph = networkx.DiGraph()
for index in range(len(self.points)):
climb = []
for i in self.climb(index, use_climb_graph=False):
climb.append(i)
# Climb until we reach a graphed node
if i in climb_graph:
break
if len(climb) == 1:
climb_graph.add_node(climb[0])
for i in range(1, len(climb)):
a = climb[i - 1]
b = climb[i]
climb_graph.add_edge(a, b, weight=self.edge_weight(a, b))
stored.value = climb_graph
return climb_graph
@property
def local_maxima(self) -> Set[int]:
"""
Points that are local maxima on the graph.
"""
with TimeAndStore(self._stored_properties, "Identifying local maxima") as stored:
if stored.value is not None:
return stored.value
stored.value = {i for i in self.climb_graph if len(self.climb_graph[i]) == 0}
return stored.value
@property
def bulk_maxima(self) -> Set[int]:
with TimeAndStore(self._stored_properties, "Identifying bulk maxima") as stored:
if stored.value is not None:
return stored.value
stored.value = self.local_maxima - self.convex_hull
return stored.value
#################
# CRITICAL TREE #
#################
@property
def max_spanning_tree(self) -> networkx.Graph:
"""
A maximum spanning tree connecting all input points
(maximum with respect to the values of the function on the graph).
"""
with TimeAndStore(self._stored_properties, "Evaluating maximum spanning tree") as stored:
if stored.value is not None:
return stored.value
if not self.average_function_edge_attributes_set:
raise Exception("Edge attributes not set correctly")
stored.value = maximum_spanning_tree(self.graph, weight="average function value")
return stored.value
@property
def critical_tree(self) -> networkx.Graph:
"""
A maximum spanning tree that connects all local maxima.
This is essentially the maximum spanning tree of the whole
graph, but pruned until it can't be pruned any more without
removing a local maxima.
"""
with TimeAndStore(self._stored_properties, "Evaluating critical tree") as stored:
if stored.value is not None:
return stored.value
stored.value = FunctionTopology.pruned_tree(self.max_spanning_tree, self.bulk_maxima)
return stored.value
@property
def critical_network(self) -> networkx.Graph:
with TimeAndStore(self._stored_properties, "Evaluating critical network") as stored:
if stored.value is not None:
return stored.value
stored.value = self.fill_critical_tree_cycles(self.critical_tree, set(self.region_centres.values()))
return stored.value
@property
def cleaved_critical_tree(self) -> Tuple[Tuple[networkx.Graph], Dict]:
with TimeAndStore(self._stored_properties, "Cleaving critical tree") as stored:
if stored.value is not None:
return stored.value
stored.value = self.cluster_tree_by_flatness(self.critical_tree, self.bulk_maxima, self.function)
return stored.value
###################
# STATIONARY TREE #
###################
@property
def min_deviation_tree(self) -> networkx.Graph:
"""
The minimum spanning tree of the graph when the edge weights are
set to the absolute function gradient along that edge.
"""
with TimeAndStore(self._stored_properties, "Generating minimum deviation tree") as stored:
if stored.value is not None:
return stored.value
if not self.abs_gradient_edge_attributes_set:
raise Exception("Edge attributes not set correctly")
stored.value = minimum_spanning_tree(self.graph, weight="abs gradient")
return stored.value
@property
def stationary_tree(self) -> networkx.Graph:
"""
The minimum deviation tree, pruned until it only spans the local maxima.
"""
with TimeAndStore(self._stored_properties, "Generating stationary tree") as stored:
if stored.value is not None:
return stored.value
stored.value = FunctionTopology.pruned_tree(self.min_deviation_tree, self.bulk_maxima)
return stored.value
@property
def cleaved_stationary_tree(self) -> Tuple[Tuple[networkx.Graph], Dict]:
with TimeAndStore(self._stored_properties, "Cleaving stationary tree") as stored:
if stored.value is not None:
return stored.value
stored.value = self.cluster_tree_by_flatness(self.stationary_tree, self.bulk_maxima, self.function)
return stored.value
###################
# EXTENDED MAXIMA #
###################
@property
def extended_maxima_families(self) -> Dict[int, Set[int]]:
"""
Returns
-------
The disconnected sets of points resulting from performing a flood
fill from each local maximum in the bulk, allowing only moves where the
function does not vary too strongly. This essentially extends and merges
local maxima into maxima families.
"""
with TimeAndStore(self._stored_properties, "Generated extended maxima families") as stored:
if stored.value is not None:
return stored.value
def deviation(i_from, i_to):
f_from = self.function[i_from]
f_to = self.function[i_to]
return abs(f_from - f_to) / (f_from - self.min_function)
floods: Dict[int, Set[int]] = dict()
for lm in self.bulk_maxima:
to_expand = {lm}
flood = set()
while len(to_expand) > 0:
expanding = to_expand.pop()
flood.add(expanding)
for n in self.graph[expanding]:
if n in to_expand or n in flood:
continue # Already discovered
if deviation(lm, n) > self.settings.stationary_value_tolerance:
continue # Too much deviation from initial maxima
to_expand.add(n)
floods[lm] = flood
def merge_floods():
for i in floods:
for j in floods:
if i != j and len(floods[i].intersection(floods[j])) > 0:
floods[i].update(floods[j])
floods.pop(j)
return True
return False
# Merge all overlapping local-maxima floods
while merge_floods():
pass
# Create a map of family id to the set of points in that family
stored.value = {i + 1: floods[x] for i, x in enumerate(floods)}
return stored.value
@property
def extended_maxima(self) -> Set[int]:
"""
Returns
-------
The union of all maxima families.
"""
with TimeAndStore(self._stored_properties, "Identifying extended maxima") as stored:
if stored.value is not None:
return stored.value
stored.value = set().union(*(self.extended_maxima_families[i] for i in self.extended_maxima_families))
return stored.value
###########
# REGIONS #
###########
@property
def regions(self) -> List[int]:
"""
For each point, the id of the maxima family whose
basin of attraction it belongs to.
"""
with TimeAndStore(self._stored_properties, "Identifying regions") as stored:
if stored.value is not None:
return stored.value
# Region -1 => unassigned
regions = [-1] * len(self.points)
# Assign extended maxima to their family
for family in self.extended_maxima_families:
for em in self.extended_maxima_families[family]:
regions[em] = family
def shortcut_possible_on_graph(j):
return regions[j] >= 0
def shortcut_possible_off_graph(j):
return regions[j] >= 0 and all(regions[n] == regions[j] for n in self.graph[j])
def shortcut_possible_monte_carlo(j):
return False
climb_method = {
GraphSteepestAscentMethod.ON_GRAPH: lambda i: self.climb(i),
GraphSteepestAscentMethod.OFF_GRAPH: self.climb_off_graph,
GraphSteepestAscentMethod.MONTE_CARLO: self.climb_monte_carlo,
}[self.settings.graph_ascent_method]
shortcut_possible = {
GraphSteepestAscentMethod.ON_GRAPH: shortcut_possible_on_graph,
GraphSteepestAscentMethod.OFF_GRAPH: shortcut_possible_off_graph,
GraphSteepestAscentMethod.MONTE_CARLO: shortcut_possible_monte_carlo
}[self.settings.graph_ascent_method]
# Assign other points according to their basin of attraction
for i in range(len(self.points)):
if regions[i] >= 0:
continue # Already assigned
climb = []
for j in climb_method(i):
climb.append(j)
if shortcut_possible(j):
# We can shortcut the
# assignment to the region of j
for k in climb:
regions[k] = regions[j]
break
if regions[i] >= 0:
continue # Assigned successfully (via shortcut)
# If the climb path ends on the convex hull
# then assign the path to the convex hull
if climb[-1] in self.convex_hull:
for k in climb:
regions[k] = 0
continue
# Assign the region of i to the region at the top of the climb
regions[i] = regions[climb[-1]]
if regions[i] < 0:
raise Exception(f"Failed to generate a region for point {i}")
stored.value = regions
return stored.value
@property
def region_count(self) -> int:
"""
The number of regions in the topology.
"""
with TimeAndStore(self._stored_properties, "Evaluating number of regions") as stored:
if stored.value is not None:
return stored.value
stored.value = len(set(self.regions))
return stored.value
@property
def region_centres(self) -> Dict[int, int]:
"""
A dictionary mapping region ids to indices
considered to be the centre of that region
"""
with TimeAndStore(self._stored_properties, "Evaluating region centres") as stored:
if stored.value is not None:
return stored.value
# A region centre is the maximum function value in that region
def max_index(region):
return max((i for i in self.local_maxima if self.regions[i] == region),
key=lambda i: self.function[i])
stored.value = {r: max_index(r) for r in set(self.regions)}
return stored.value
@property
def region_paths(self) -> Dict[Tuple[int, int], List[int]]:
"""
A dictionary mapping a pair of neighbouring regions
to the maximum-function (critical) path between them.
The paths are indexed by a pair of region ids in ascending order.
"""
with TimeAndStore(self._stored_properties, "Evaluating region paths") as stored:
if stored.value is not None:
return stored.value
region_paths = dict()
for i, i_centre in self.region_centres.items():
for j, j_centre in self.region_centres.items():
if i >= j:
continue
if i_centre not in self.critical_network:
assert i_centre in self.convex_hull
continue
if j_centre not in self.critical_network:
assert j_centre in self.convex_hull
continue
path = shortest_path(self.critical_network, source=i_centre, target=j_centre)
if len({self.regions[p] for p in path}) != 2:
continue # Region paths should only pass through two regions
region_paths[(i, j)] = path
stored.value = region_paths
return stored.value
@property
def region_boundaries(self) -> Dict[Tuple[int, int], Set[int]]:
"""
Returns
-------
boundaries:
A map from a pair of regions (i, j) to the set of points in
region i that are on the boundary with region j.
"""
with TimeAndStore(self._stored_properties, "Evaluating region boundaries") as stored:
if stored.value is not None:
return stored.value
region_boundaries: Dict[Tuple[int, int], Set[int]] = defaultdict(lambda: set())
for i, ri in enumerate(self.regions):
for n in self.graph[i]:
rn = self.regions[n]
if rn != ri:
region_boundaries[(ri, rn)].add(i)
stored.value = region_boundaries
return stored.value
@property
def regions_connected_by_saddle_point(self) -> Dict[int, Set[int]]:
"""
Returns
-------
critical_links:
A map from a region to the set of regions linked to it via a saddle point.
"""
with TimeAndStore(self._stored_properties, "Evaluating saddle-point-linked regions") as stored:
if stored.value is not None:
return stored.value
links: Dict[int, Set[int]] = defaultdict(lambda: set())
for key in self.region_boundaries:
boundary = self.region_boundaries[key]
critical_point = max(boundary, key=lambda p: self.function[p])
bordering = set(self.regions[n] for n in self.graph[critical_point])
if len(bordering) > 2:
continue # Not critically linked
# Add the critical link both ways
links[key[0]].add(key[1])
links[key[1]].add(key[0])
stored.value = links
return stored.value
@property
def saddle_linked_region_graph(self) -> networkx.Graph:
"""
Returns
-------
graph:
The graph with edges between saddle-point-linked region centres.
"""
# Work out the boundaries between regions
edges = []
for ri, ci in self.region_centres.items():
for rj, cj in self.region_centres.items():
if ci >= cj:
continue # Avoid double counting edges
if ri == rj:
continue # Don't connect points in same region
if ri in self.regions_connected_by_saddle_point[rj]:
edges.append([ci, cj])
filled_tree = networkx.Graph()
filled_tree.add_edges_from(edges)
return filled_tree
###########
# METHODS #
###########
def region_charges(self, weights: Sequence[float]) -> Dict[int, float]:
"""
Evaluate the sum of the given weights array for each distinct region.
Parameters
----------
weights: Sequence[float]
A weight for each point, to sum over each region.
Returns
-------
region_charges: Dict[int, float]
For each region id (int), the summed weight over that region (float).
"""
assert len(weights) == len(self.points)
with TimeAndStore(self._stored_properties, "Evaluating region charges") as stored:
if stored.value is not None:
return stored.value
result = dict()
for i, weight in enumerate(weights):
weight *= self.function[i]
r = self.regions[i]
if r in result:
result[r] += weight
else:
result[r] = weight
stored.value = result
return stored.value
def edge_weight(self, i: int, j: int) -> float:
"""
Evaluate the weight that should be assigned
to an edge connecting indices i and j.
Parameters
----------
i: int
Index of first node in the graph.
j: int
Index of second node in the graph.
"""
scaled_f = (self.function[i] + self.function[j]) * 0.5
scaled_f = (scaled_f - self.min_function) / (self.max_function - self.min_function)
return scaled_f
def nearest_point(self, location) -> int:
"""
Find the nearest point on the graph to the given location.
"""
dists, index = self.kd_tree.query(location, k=1)
if index == len(self.points):
raise Exception(f"Could not identify nearest neighbour of point {location}")
return index
def climb_off_graph(self, index: int) -> Iterator[int]:
"""
Generate a set of indices along which self.function increases,
according to a steepest-gradient path that is allowed to go
off-graph.
Parameters
----------
index:
The index to start climbing from (will be yielded immediately).
Yields
------
index: int
The next index along the path.
"""
def steepest_ascent_direction(i):
# Fallback is just steepest-ascent direction
for j in self.climb(i):
if j != i:
return self.points[j] - self.points[i]
# Start at the point at the given index
x = np.array(self.points[index])
visited = set()
iteration = 0
while True:
# Work out the nearest grid point to x
i = self.nearest_point(x)
iteration += 1
if iteration % 1000 == 0:
self.print(f"Reached off-graph climb iteration {iteration} for point {index}. Got to point {i} x = {x}")
if i not in visited:
yield i
visited.add(i)
if i in self.local_maxima:
return # We've reached the top
# Use the nearest-neighbour gradient
g = self.gradient[i]
g_norm = np.linalg.norm(g)
if g_norm < 1e-5:
g = steepest_ascent_direction(i)
g_norm = np.linalg.norm(g)
# Use the minimum edge size as our step size
s = min(np.linalg.norm(self.points[j] - self.points[i]) for j in self.graph[i])
# Make a step
step = s * g / g_norm
x += step
def climb(self, index: int, use_climb_graph: bool = True) -> Iterator[int]:
"""
Generate a set of indices along which self.function
increases, starting at the given index. The indices
will be generated by making moves along the path with
the largest gradient in the self.neighbours network.
Parameters
----------
index: int
The index to start climbing from (will be yielded immediately).
use_climb_graph: bool
True if we should use the already-constructed
climb_graph to speed up generation of the path.
Yields
------
index: int
The next index along the path.
"""
yield index
if use_climb_graph:
# Use the already-constructed climb graph
i = index
while len(self.climb_graph[i]) > 0:
if len(self.climb_graph[i]) > 1:
raise Exception("Climb graph is not one-to-one!")
for j in self.climb_graph[i]:
i = j
yield i
return
visited = {index}
# Climb self.graph manually
while True:
# Evaluate the function and coordinates
# at the current index
f0 = self.function[index]
p0 = self.points[index]
max_index = index
max_dfdx = -float("inf")
# Search neighbours of the current
# point for the largest gradient
for n in self.graph[index]:
if n == index:
# Don't allow self-moves
continue
fn = self.function[n]
if fn < f0:
# Don't allow downhill moves
continue
if n in visited:
# Don't allow moves to already-visited points
# this allows the climber to explore regions
# where the function is flat, without getting stuck
# in an infinite loop.
continue
dfdx = fn - f0
dfdx /= np.linalg.norm(self.points[n] - p0)
if dfdx > max_dfdx:
# Found a larger-gradient move
max_index = n
max_dfdx = dfdx
if max_index == index:
# No move made => we're at a maximum
return
# Make move along the maximum gradient path
index = max_index
visited.add(index)
yield index
def climb_monte_carlo(self, index: int) -> Iterator[int]:
"""
Generate a set of indices along which self.function increases,
according to a probability along each upward direction, so that
the average move aligns with the gradient.
Parameters
----------
index:
The index to start climbing from (will be yielded immediately).
Yields
------
index: int
The next index along the path.
"""
raise NotImplementedError()
def fill_critical_tree_cycles(self, tree: networkx.Graph, nodes: Set[int]) -> networkx.Graph:
"""
Adds missing critical paths to the critical tree, by attempting
to add critical paths through subgraphs.
Parameters
----------
tree: networkx.Graph
The tree to fill cycles in.
Returns
-------
filled_tree: networkx.Graph
The graph with cycles in the tree filled.
"""
new_edges = []
nodes = nodes.intersection(tree.nodes)
pairs = [[n1, n2] for n1 in nodes for n2 in nodes if n1 < n2]
subgraphs = dict()
subtrees = dict()
subpaths = dict()
for source, target in pairs:
# Check if already critically linked on tree
path = shortest_path(tree, source=source, target=target)
if len(set(self.regions[p] for p in path)) <= 2:
self.print(f"Points {source} and {target} already critically linked")
continue
# Get regions to path between
r_source = self.regions[source]
r_target = self.regions[target]
if r_source != r_target and (r_source, r_target) not in self.region_boundaries:
continue # These regions do not border one another
# Check if subgraph/tree has already been generated fro this pair of regions
key = (r_source, r_target) if r_source < r_target else (r_target, r_source)
if key in subgraphs:
subgraph = subgraphs[key]
subtree = subtrees[key]
else:
self.print(f"Generating subgraph for regions {r_source} and {r_target}...")
subnodes = (n for n in self.graph if self.regions[n] in {r_source, r_target})
subgraph = subgraphs[key] = networkx.subgraph(self.graph, subnodes)
subtree = subtrees[key] = maximum_spanning_tree(subgraph, weight="average function value")
# Check if subpath has already been generated
key = (source, target)
if key in subpaths:
subpath = subpaths[key]
else:
self.print(f"Generating subpath for points {source} and {target}...")
subpath = subpaths[key] = shortest_path(subtree, source=source, target=target)
def on_edge(i):
return len(set(self.regions[j] for j in self.graph[i]) - {r_source, r_target}) > 0
# A critical path touches the edge of r_source \cup r_target => it wants to go through
# another region => r_source and r_target are not critically linked
if any(on_edge(p) for p in subpath):
self.print(f"Points {source} and {target} are not critically linked")
continue
for i in range(1, len(subpath)):
new_edges.append((subpath[i - 1], subpath[i]))
tree = tree.copy()
tree.add_edges_from(new_edges)
return tree
##################
# SAVING/LOADING #