forked from aimacode/aima-julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.jl
1597 lines (1368 loc) · 55.3 KB
/
search.jl
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 Base: ==, length, in, eltype;
export Problem, InstrumentedProblem,
actions, get_result, goal_test, path_cost, value,
format_instrumented_results,
Node, expand, child_node, solution, path, ==,
search,
GAState, mate, mutate,
tree_search, graph_search,
breadth_first_tree_search, depth_first_tree_search, depth_first_graph_search,
breadth_first_search, best_first_graph_search, uniform_cost_search,
recursive_dls, depth_limited_search, iterative_deepening_search,
greedy_best_first_graph_search,
Graph, make_undirected, connect_nodes, get_linked_nodes, get_nodes,
UndirectedGraph, RandomGraph,
GraphProblem,
astar_search, recursive_best_first_search,
hill_climbing, exp_schedule, simulated_annealing,
or_search, and_search, and_or_graph_search,
OnlineDFSAgentProgram, update_state, execute,
OnlineSearchProblem, LRTAStarAgentProgram,
learning_realtime_astar_cost,
genetic_search, genetic_algorithm,
NQueensProblem, conflict, conflicted,
random_boggle, print_boggle, boggle_neighbors, int_sqrt,
WordList, lookup, length, in,
BoggleFinder, set_board, find, words, score,
boggle_hill_climbing, mutate_boggle,
execute_searcher, compare_searchers, beautify_node;
#=
Problem is a abstract problem that contains a initial state and goal state.
=#
mutable struct Problem <: AbstractProblem
initial::String
goal::Union{Nothing, String}
function Problem(initial_state::String; goal_state::Union{Nothing, String}=nothing)
return new(initial_state, goal_state);
end
end
"""
actions(ap::T, state::String) where {T <: AbstractProblem}
Return an array of possible actions that can be executed in the given state 'state'.
"""
function actions(ap::T, state::String) where {T <: AbstractProblem}
println("actions() is not implemented yet for ", typeof(ap), "!");
nothing;
end
"""
get_result(ap::T, state::String, action::String) where {T <: AbstractProblem}
Return the resulting state from executing the given action 'action' in the given state 'state'.
"""
function get_result(ap::T, state::String, action::String) where {T <: AbstractProblem}
println("get_result() is not implemented yet for ", typeof(ap), "!");
nothing;
end
"""
goal_test(ap::T, state::String) where {T <: AbstractProblem}
Return a boolean value representing whether the given state 'state' is a goal state in the given
problem 'ap'.
"""
function goal_test(ap::T, state::String) where {T <: AbstractProblem}
return ap.goal == state;
end
"""
path_cost(ap::T, cost::Float64, state1::String, action::String, state2::String) where {T <: AbstractProblem}
path_cost(ap::T, cost::Float64, state1::AbstractVector, action::Int64, state2::AbstractVector) where {T <: AbstractProblem}
Return the cost of a solution path arriving at 'state2' from 'state1' with the given action 'action' and
cost 'cost' to arrive at 'state1'. The default path_cost() method costs 1 for every step in a path.
"""
function path_cost(ap::T, cost::Float64, state1::String, action::String, state2::String) where {T <: AbstractProblem}
return cost + 1;
end
function path_cost(ap::T, cost::Float64, state1::AbstractVector, action::Int64, state2::AbstractVector) where {T <: AbstractProblem}
return cost + 1;
end
"""
value(ap::T, state::String) where {T <: AbstractProblem}
Return a value for the given state 'state' in the given problem 'ap'.
This value is used in optimization problems such as hill climbing or simulated annealing.
"""
function value(ap::T, state::String) where {T <: AbstractProblem}
println("value() is not implemented yet for ", typeof(ap), "!");
nothing;
end
#=
InstrumentedProblem is a AbstractProblem implementation that wraps another AbstractProblem
implementation and tracks the number of function calls made. This problem is used in
compare_searchers() and execute_searcher().
=#
mutable struct InstrumentedProblem <: AbstractProblem
problem::AbstractProblem
actions::Int64
results::Int64
goal_tests::Int64
found # can be any DataType, but check for Nothing DataType later
function InstrumentedProblem(ap::T) where {T <: AbstractProblem}
return new(ap, Int64(0), Int64(0), Int64(0), nothing);
end
end
function actions(ap::InstrumentedProblem, state::AbstractVector)
ap.actions = ap.actions + 1;
return actions(ap.problem, state);
end
function actions(ap::InstrumentedProblem, state::String)
ap.actions = ap.actions + 1;
return actions(ap.problem, state);
end
function get_result(ap::InstrumentedProblem, state::String, action::String)
ap.results = ap.results + 1;
return get_result(ap.problem, state, action);
end
function get_result(ap::InstrumentedProblem, state::AbstractVector, action::Int64)
ap.results = ap.results + 1;
return get_result(ap.problem, state, action);
end
function goal_test(ap::InstrumentedProblem, state::String)
ap.goal_tests = ap.goal_tests + 1;
local result::Bool = goal_test(ap.problem, state);
if (result)
ap.found = state;
end
return result;
end
function goal_test(ap::InstrumentedProblem, state::AbstractVector)
ap.goal_tests = ap.goal_tests + 1;
local result::Bool = goal_test(ap.problem, state);
if (result)
ap.found = state;
end
return result;
end
function path_cost(ap::InstrumentedProblem, cost::Float64, state1::String, action::String, state2::String)
return path_cost(ap.problem, cost, state1, action, state2);
end
function path_cost(ap::InstrumentedProblem, cost::Float64, state1::AbstractVector, action::Int64, state2::AbstractVector)
return path_cost(ap.problem, cost, state1, action, state2);
end
function value(ap::InstrumentedProblem, state::String)
return value(ap.problem, state);
end
function value(ap::InstrumentedProblem, state::AbstractVector)
return value(ap.problem, state);
end
function format_instrumented_results(ap::InstrumentedProblem)
return @sprintf("<%4d/%4d/%4d/%s>", ap.actions, ap.goal_tests, ap.results, string(ap.found));
end
# A node should not exist without a state.
mutable struct Node{T}
state::T
path_cost::Float64
depth::UInt32
action::Union{Nothing, String, Int64, Tuple}
parent::Union{Nothing, Node}
f::Float64
function Node{T}(state::T; parent::Union{Nothing, Node}=nothing, action::Union{Nothing, String, Int64, Tuple}=nothing, path_cost::Float64=0.0, f::Union{Nothing, Float64}=nothing) where T
nn = new(state, path_cost, UInt32(0), action, parent);
if (typeof(parent) <: Node)
nn.depth = UInt32(parent.depth + 1);
end
if (typeof(f) <: Float64)
nn.f = f;
end
return nn;
end
end
"""
expand(n::Node, ap::T) where {T <: AbstractProblem}
Return an array of nodes reachable by 1 step from the given node 'n' in the problem 'ap'.
"""
function expand(n::Node, ap::T) where {T <: AbstractProblem}
return collect(child_node(n, ap, act) for act in actions(ap, n.state));
end
"""
child_node(n::Node, ap::T, action::String) where {T <: AbstractProblem}
Return a child node for the given node 'n' in problem 'ap' after executing the action 'action' (Fig. 3.10).
"""
function child_node(n::Node, ap::T, action::String) where {T <: AbstractProblem}
local next_node = get_result(ap, n.state, action);
return Node{typeof(next_node)}(next_node, parent=n, action=action, path_cost=path_cost(ap, n.path_cost, n.state, action, next_node));
end
function child_node(n::Node, ap::T, action::Int64) where {T <: AbstractProblem}
local next_node = get_result(ap, n.state, action);
return Node{typeof(next_node)}(next_node, parent=n, action=action, path_cost=path_cost(ap, n.path_cost, n.state, action, next_node));
end
function child_node(n::Node, ap::T, action::Tuple) where {T <: AbstractProblem}
local next_node = get_result(ap, n.state, action);
return Node{typeof(next_node)}(next_node, parent=n, action=action, path_cost=path_cost(ap, n.path_cost, n.state, action, next_node));
end
"""
solution(n::Node)
Return an array of actions to get from the root node of node 'n' to the given node 'n'.
"""
function solution(n::Node)
local path_sequence = path(n);
return [node.action for node in path_sequence[2:length(path_sequence)]];
end
"""
path(n::Node)
Return the path between the root node of node 'n' to the given node 'n' as an array of nodes.
"""
function path(n::Node)
local node = n;
local path_back = [];
while true
push!(path_back, node);
if (!(node.parent === nothing))
node = node.parent;
else
# The root node does not have a parent node.
break;
end
end
path_back = reverse(path_back);
return path_back;
end
function ==(n1::Node, n2::Node)
return (n1.state == n2.state);
end
#=
SimpleProblemSolvingAgentProgram is a abstract problem solving agent (Fig. 3.1).
=#
mutable struct SimpleProblemSolvingAgentProgram <: AgentProgram
state::Union{Nothing, String}
goal::Union{Nothing, String}
seq::Array{String, 1}
problem::Union{Nothing, Problem}
function SimpleProblemSolvingAgentProgram(;initial_state::Union{Nothing, String}=nothing)
return new(initial_state, nothing, Array{String, 1}(), nothing);
end
end
function execute(spsap::SimpleProblemSolvingAgentProgram, percept::Tuple{Any, Any})
spsap.state = update_state(spsap, spsap.state, percept);
if (length(spsap.seq) == 0)
spsap.goal = formulate_problem(spsap, spsap.state);
spsap.problem = forumate_problem(spsap, spsap.state, spsap.goal);
spsap.seq = search(spsap, spsap.problem);
if (length(spsap.seq) == 0)
return Nothing;
end
end
local action = popfirst!(spsap.seq);
return action;
end
function update_state(spsap::SimpleProblemSolvingAgentProgram, state::String, percept::Tuple{Any, Any})
println("update_state() is not implemented yet for ", typeof(spsap), "!");
nothing;
end
function formulate_goal(spsap::SimpleProblemSolvingAgentProgram, state::String)
println("formulate_goal() is not implemented yet for ", typeof(spsap), "!");
nothing;
end
function formulate_problem(spsap::SimpleProblemSolvingAgentProgram, state::String, goal::String)
println("formulate_problem() is not implemented yet for ", typeof(spsap), "!");
nothing;
end
function search(spsap::SimpleProblemSolvingAgentProgram, problem::T) where {T <: AbstractProblem}
println("search() is not implemented yet for ", typeof(spsap), "!");
nothing;
end
struct GAState
genes::Array{Any, 1}
function GAState(genes::Array{Any, 1})
return new(Array{Any,1}(deepcopy(genes)));
end
end
function mate(ga_state::T, other::T) where {T <: GAState}
local c = rand(RandomDeviceInstance, range(1, stop=length(ga_state.genes)));
local new_ga_state = deepcopy(ga_state[1:c]);
for element in other.genes[(c + 1):length(other.genes)]
push!(new_ga_state, element);
end
return new_ga_state;
end
function mutate(ga_state::T) where {T <: GAState}
println("mutate() is not implemented yet for ", typeof(ga_state), "!");
nothing;
end
"""
tree_search{T1 <: AbstractProblem, T2 <: Queue}(problem::T1, frontier::T2)
Search the given problem by using the general tree search algorithm (Fig. 3.7) and return the node solution.
"""
function tree_search(problem::T1, frontier::T2) where {T1 <: AbstractProblem, T2 <: Queue}
push!(frontier, Node{typeof(problem.initial)}(problem.initial));
while (length(frontier) != 0)
local node = pop!(frontier);
if (goal_test(problem, node.state))
return node;
end
extend!(frontier, expand(node, problem));
end
return nothing;
end
function tree_search(problem::InstrumentedProblem, frontier::T) where {T <: Queue}
push!(frontier, Node{typeof(problem.problem.initial)}(problem.problem.initial));
while (length(frontier) != 0)
local node = pop!(frontier);
if (goal_test(problem, node.state))
return node;
end
extend!(frontier, expand(node, problem));
end
return nothing;
end
"""
graph_search{T1 <: AbstractProblem, T2 <: Queue}(problem::T1, frontier::T2)
Search the given problem by using the general graph search algorithm (Fig. 3.7) and return the node solution.
The uniform cost algorithm (Fig. 3.14) should be used when the frontier is a priority queue.
"""
function graph_search(problem::T1, frontier::T2) where {T1 <: AbstractProblem, T2 <: Queue}
local explored::Set;
if (typeof(problem.initial) <: Tuple)
explored = Set{NTuple}();
else
explored = Set{typeof(problem.initial)}();
end
push!(frontier, Node{typeof(problem.initial)}(problem.initial));
while (length(frontier) != 0)
local node = pop!(frontier);
if (goal_test(problem, node.state))
return node;
end
push!(explored, node.state);
extend!(frontier, collect(child_node for child_node in expand(node, problem)
if (!(child_node.state in explored) && !(child_node in frontier))));
end
return nothing;
end
function graph_search(problem::InstrumentedProblem, frontier::T) where {T <: Queue}
local explored::Set;
if (typeof(problem.problem.initial) <: Tuple)
explored = Set{NTuple}();
else
explored = Set{typeof(problem.problem.initial)}();
end
push!(frontier, Node{typeof(problem.problem.initial)}(problem.problem.initial));
while (length(frontier) != 0)
local node = pop!(frontier);
if (goal_test(problem, node.state))
return node;
end
push!(explored, node.state);
extend!(frontier, collect(child_node for child_node in expand(node, problem)
if (!(child_node.state in explored) && !(child_node in frontier))));
end
return nothing;
end
"""
breadth_first_tree_search(problem::T) where {T <: AbstractProblem}
Search the shallowest nodes in the search tree first.
"""
function breadth_first_tree_search(problem::T) where {T <: AbstractProblem}
return tree_search(problem, FIFOQueue());
end
"""
depth_first_tree_search(problem::T) where {T <: AbstractProblem}
Search the deepest nodes in the search tree first.
"""
function depth_first_tree_search(problem::T) where {T <: AbstractProblem}
return tree_search(problem, Stack());
end
"""
depth_first_graph_search(problem::T) where {T <: AbstractProblem}
Search the deepest nodes in the search tree first.
"""
function depth_first_graph_search(problem::T) where {T <: AbstractProblem}
return graph_search(problem, Stack());
end
"""
breadth_first_search(problem::T) where {T <: AbstractProblem}
breadth_first_search(problem::InstrumentedProblem)
Return a solution by using the breadth-first search algorithm (Fig. 3.11)
on the given problem 'problem'. Otherwise, return 'nothing' on failure.
"""
function breadth_first_search(problem::T) where {T <: AbstractProblem}
local node = Node{typeof(problem.initial)}(problem.initial);
if (goal_test(problem, node.state))
return node;
end
local frontier = FIFOQueue();
push!(frontier, node);
local explored = Set{String}();
while (length(frontier) != 0)
node = pop!(frontier);
push!(explored, node.state);
for child_node in expand(node, problem)
if (!(child_node.state in explored) && !(child_node in frontier))
if (goal_test(problem, child_node.state))
return child_node;
end
push!(frontier, child_node);
end
end
end
return nothing;
end
function breadth_first_search(problem::InstrumentedProblem)
local node = Node{typeof(problem.problem.initial)}(problem.problem.initial);
if (goal_test(problem, node.state))
return node;
end
local frontier = FIFOQueue();
push!(frontier, node);
local explored = Set{String}();
while (length(frontier) != 0)
node = pop!(frontier);
push!(explored, node.state);
for child_node in expand(node, problem)
if (!(child_node.state in explored) && !(child_node in frontier))
if (goal_test(problem, child_node.state))
return child_node;
end
push!(frontier, child_node);
end
end
end
return nothing;
end
"""
best_first_graph_search(problem::T, f::Function) where {T <: AbstractProblem}
Search the nodes in the given problem 'problem' by visiting the nodes with the lowest
scores returned by f(). If f() is a heuristics estimate function to the goal state, then
this function becomes greedy best first search. If f() is a function that gets the node's
depth, then this function becomes breadth-first search.
Returns a solution if found, otherwise returns 'nothing' on failure.
This function uses f as a Function, because using f as an MemoizedFunction exhibits unusual
behavior when relying on MemoizedFunction by producing unexpected results.
"""
function best_first_graph_search(problem::T, f::Function) where {T <: AbstractProblem}
local node = Node{typeof(problem.initial)}(problem.initial);
if (goal_test(problem, node.state))
return node;
end
local frontier = PQueue();
push!(frontier, node, f);
local explored = Set{typeof(problem.initial)}();
while (length(frontier) != 0)
node = pop!(frontier);
if (goal_test(problem, node.state))
return node;
end
push!(explored, node.state);
for child_node in expand(node, problem)
if (!(child_node.state in explored) &&
!(child_node in collect(getindex(x, 2) for x in frontier.array)))
push!(frontier, child_node, f);
elseif (child_node in [getindex(x, 2) for x in frontier.array])
# Recall that Nodes can share the same state and different values for other fields.
local existing_node = pop!(collect(getindex(x, 2)
for x in frontier.array
if (getindex(x, 2) == child_node)));
if (f(child_node) < f(existing_node))
delete!(frontier, existing_node);
push!(frontier, child_node, f);
end
end
end
end
return nothing;
end
"""
uniform_cost_search(problem::T) where {T <: AbstractProblem}
Search the given problem by using the uniform cost algorithm (Fig. 3.14) and return the node solution.
solution() can be used on the node solution to reconstruct the path taken to the solution.
"""
function uniform_cost_search(problem::T) where {T <: AbstractProblem}
return best_first_graph_search(problem, (function(n::Node)return n.path_cost;end));
end
function recursive_dls(node::Node, problem::T, limit::Int64) where {T <: AbstractProblem}
if (goal_test(problem, node.state))
return node;
elseif (node.depth == limit)
return "cutoff";
else
local cutoff_occurred = false;
for child_node in expand(node, problem)
local result = recursive_dls(child_node, problem, limit);
if (result == "cutoff")
cutoff_occurred = true;
elseif (!(typeof(result) <: Nothing))
return result;
end
end
return if_(cutoff_occurred, "cutoff", nothing);
end
end;
"""
depth_limited_search(problem::T; limit::Int64) where {T <: AbstractProblem}
Search the given problem by using the depth limited tree search algorithm (Fig. 3.17)
and return the node solution if a solution was found. Otherwise, this function returns 'nothing'.
solution() can be used on the node solution to reconstruct the path taken to the solution.
"""
function depth_limited_search(problem::T; limit::Int64=50) where {T <: AbstractProblem}
return recursive_dls(Node{typeof(problem.initial)}(problem.initial), problem, limit);
end
function depth_limited_search(problem::InstrumentedProblem; limit::Int64=50)
return recursive_dls(Node{typeof(problem.problem.initial)}(problem.problem.initial), problem, limit);
end
"""
iterative_deepening_search(problem::T) where {T <: AbstractProblem}
Search the given problem by using the iterative deepening search algorithm (Fig. 3.18)
and return the node solution if a solution was found. Otherwise, this function returns 'nothing'.
solution() can be used on the node solution to reconstruct the path taken to the solution.
"""
function iterative_deepening_search(problem::T) where {T <: AbstractProblem}
for depth in 1:typemax(Int64)
local result = depth_limited_search(problem, limit=depth)
if (result != "cutoff")
return result;
end
end
return nothing;
end
const greedy_best_first_graph_search = best_first_graph_search;
#=
Graph is a graph that consists of nodes (vertices) and edges (links).
The Graph constructor uses the keyword 'directed' to specify if the graph
is directed or undirected.
For an example Graph instance:
Graph(dict=Dict([("A", Dict([("B", 1), ("C", 2)]))]))
The example Graph is a directed graph with 3 vertices ("A", "B", and "C")
and link "A"=>"B" (length 1) and "A"=>"C" (length 2).
=#
struct Graph{N}
dict::Dict{N, Any}
locations::Dict{N, Tuple{Any, Any}}
directed::Bool
function Graph{N}(;dict::Union{Nothing, Dict{N, }}=nothing, locations::Union{Nothing, Dict{N, Tuple{Any, Any}}}=nothing, directed::Bool=true) where N
local ng::Graph;
if ((typeof(dict) <: Nothing) && (typeof(locations) <: Nothing))
ng = new(Dict{Any, Any}(), Dict{Any, Tuple{Any, Any}}(), Bool(directed));
elseif (typeof(locations) <: Nothing)
ng = new(Dict{eltype(dict.keys), Any}(dict), Dict{Any, Tuple{Any, Any}}(), Bool(directed));
else
ng = new(Dict{eltype(dict.keys), Any}(dict), Dict{eltype(locations.keys), Tuple{Any, Any}}(locations), Bool(directed));
end
if (!ng.directed)
make_undirected(ng);
end
return ng;
end
function Graph{N}(graph::Graph{N}) where N
return new(Dict{Any, Any}(graph.dict), Dict{String, Tuple{Any, Any}}(graph.locations), Bool(graph.directed));
end
end
eltype(::Type{<:Graph{T}}) where {T} = T
function make_undirected(graph::Graph)
for location_A in keys(graph.dict)
for (location_B, d) in graph.dict[location_A]
connect_nodes(graph, location_B, location_A, distance=d);
end
end
end
"""
connect_nodes(graph::Graph{N}, A::N, B::N; distance::Int64=Int64(1)) where N
Add a link between Node 'A' to Node 'B'. If the graph is undirected, then add
the inverse link from Node 'B' to Node 'A'.
"""
function connect_nodes(graph::Graph{N}, A::N, B::N; distance::Int64=Int64(1)) where N
get!(graph.dict, A, Dict{String, Int64}())[B]=distance;
if (!graph.directed)
get!(graph.dict, B, Dict{String, Int64}())[A]=distance;
end
nothing;
end
"""
get_linked_nodes(graph::Graph{N}, a::N; b::Union{Nothing, N}=nothing) where N
Return a dictionary of nodes and their distances if the 'b' keyword is not given.
Otherwise, return the distance between 'a' and 'b'.
"""
function get_linked_nodes(graph::Graph{N}, a::N; b::Union{Nothing, N}=nothing) where N
local linked = get!(graph.dict, a, Dict{Any, Any}());
if (typeof(b) <: Nothing)
return linked;
else
return get(linked, b, nothing);
end
end
function get_nodes(graph::Graph)
return collect(keys(graph.dict));
end
"""
UndirectedGraph(dict::Dict{T, }, locations::Dict{T, Tuple{Any, Any}}) where T
UndirectedGraph()
Return an undirected graph from the given dictionary of links 'dict' and dictionary
of locations 'locations' if given.
"""
function UndirectedGraph(dict::Dict{T, }, locations::Dict{T, Tuple{Any, Any}}) where T
return Graph{eltype(dict.keys)}(dict=dict, locations=locations, directed=false);
end
function UndirectedGraph()
return Graph{Any}(directed=false);
end
"""
RandomGraph()
Return a random graph with the specified nodes and number of links.
"""
function RandomGraph(;nodes::UnitRange=1:10,
min_links::Int64=2,
width::Int64=400,
height::Int64=300,
curvature::Function=(function()
return (0.4*rand(RandomDeviceInstance)) + 1.1;
end))
local g = UndirectedGraph();
for node in nodes
g.locations[node] = Tuple((rand(RandomDeviceInstance, 1:width), rand(RandomDeviceInstance, 1:height)));
end
for i in 1:min_link
for node in nodes
if (get_linked_nodes(g, node) < min_links)
local here = g.locations[node];
local neighbor = argmin(nodes, (function(n, ; graph::Graph=g, current_node::Node=node, current_location::Tuple=here)
if (n == current_node || get_linked_nodes(graph, current_node, n) != nothing)
return Inf;
end
return distance(g.locations[n], current_location);
end));
local d = distance(g.locations[neighbor], here) * curvature();
connect(g, node, neighbor, Int64(floor(d)));
end
end
end
return g;
end
#=
GraphProblem is the problem of searching a graph from one node to another node.
=#
struct GraphProblem <: AbstractProblem
initial::String
goal::String
graph::Graph
h::MemoizedFunction
function GraphProblem(initial_state::String, goal_state::String, graph::Graph)
return new(initial_state, goal_state, Graph{eltype(graph)}(graph), MemoizedFunction(initial_to_goal_distance));
end
end
function actions(gp::GraphProblem, loc::String)
return collect(keys(get_linked_nodes(gp.graph,loc)));
end
function get_result(gp::GraphProblem, state::String, action::String)
return action;
end
function path_cost(gp::GraphProblem, current_cost::Float64, location_A::String, action::String, location_B::String)
local AB_distance::Float64;
if (haskey(gp.graph.dict, location_A) && haskey(gp.graph.dict[location_A], location_B))
AB_distance= Float64(get_linked_nodes(gp.graph,location_A, b=location_B));
else
AB_distance = Float64(Inf);
end
return current_cost + AB_distance;
end
"""
initial_to_goal_distance(gp::GraphProblem, n::Node)
Compute the straight line distance between the initial state and goal state.
"""
function initial_to_goal_distance(gp::GraphProblem, n::Node)
local locations = gp.graph.locations;
if (isempty(locations))
return Inf;
else
return Float64(floor(distance(locations[n.state], locations[gp.goal])));
end
end
function initial_to_goal_distance(gp::InstrumentedProblem, n::Node)
local locations = gp.problem.graph.locations;
if (isempty(locations))
return Inf;
else
return Float64(floor(distance(locations[n.state], locations[gp.problem.goal])));
end
end
"""
astar_search(problem::GraphProblem; h::Union{Nothing, Function}=nothing)
Apply the A* search (best-first graph search with f(n)=g(n)+h(n)) to the given problem 'problem'.
If the 'h' keyword is not used, this function uses the function problem.h.
This function uses mh as a Function, because using mh as an MemoizedFunction exhibits unusual
behavior when relying on MemoizedFunction by producing unexpected results.
"""
function astar_search(problem::GraphProblem; h::Union{Nothing, Function}=nothing)
local mh::Function;
if (!(typeof(h) <: Nothing))
mh = h;
else
mh = problem.h.f;
end
return best_first_graph_search(problem,
(function(node::Node; h::Function=mh, prob::GraphProblem=problem)
return node.path_cost + h(prob, node);
end));
end
"""
RBFS(problem::T1, node::T2, flmt::Float64, h::MemoizedFunction) where {T1 <: AbstractProblem, T2 <: Node}
Recursively calls RBFS() with a new 'flmt' value and returns its solution to recursive_best_first_search().
"""
function RBFS(problem::T1, node::T2, flmt::Float64, h::MemoizedFunction) where {T1 <: AbstractProblem, T2 <: Node}
if (goal_test(problem, node.state))
return node, 0.0;
end
local successors = expand(node, problem);
if (length(successors) == 0);
return node, Inf;
end
for successor in successors
successor.f = max(successor.path_cost + eval_memoized_function(h, problem, successor), node.f);
end
while (true)
sort!(successors, lt=(function(n1::Node, n2::Node)return isless(n1.f, n2.f);end));
local best::Node = successors[1];
if (best.f > flmt)
return nothing, best.f;
end
local alternative::Float64;
if (length(successors) > 1)
alternative = successors[1].f;
else
alternative = Inf;
end
result, best.f = RBFS(problem, best, min(flmt, alternative), h);
if (!(result === nothing))
return result, best.f;
end
end
end
"""
recursive_best_first_search(problem::T; h::Union{Nothing, MemoizedFunction}) where {T <: AbstractProblem}
Search the given problem by using the recursive best first search algorithm (Fig. 3.26)
and return the node solution.
solution() can be used on the node solution to reconstruct the path taken to the solution.
"""
function recursive_best_first_search(problem::T; h::Union{Nothing, MemoizedFunction}=nothing) where {T <: AbstractProblem}
local mh::MemoizedFunction; #memoized h(n) function
if (!(typeof(h) <: Nothing))
mh = MemoizedFunction(h);
else
mh = problem.h;
end
local node = Node{typeof(problem.initial)}(problem.initial);
node.f = eval_memoized_function(mh, problem, node);
result, bestf = RBFS(problem, node, Inf, mh);
return result;
end
function recursive_best_first_search(problem::InstrumentedProblem; h::Union{Nothing, MemoizedFunction}=nothing)
local mh::MemoizedFunction; #memoized h(n) function
if (!(typeof(h) <: Nothing))
mh = MemoizedFunction(h);
else
mh = problem.problem.h;
end
local node = Node{typeof(problem.problem.initial)}(problem.problem.initial);
node.f = eval_memoized_function(mh, problem, node);
result, bestf = RBFS(problem, node, Inf, mh);
return result;
end
"""
hill_climbing(problem::T) where {T <: AbstractProblem}
Return a state that is a local maximum for the given problem 'problem' by using
the hill-climbing search algorithm (Fig. 4.2) on the initial state of the problem.
"""
function hill_climbing(problem::T) where {T <: AbstractProblem}
local current_node = Node{typeof(problem.initial)}(problem.initial);
while (true)
local neighbors = expand(current_node, problem);
if (length(neighbors) == 0)
break;
end
local neighbor = argmax_random_tie(neighbors,
(function(n::Node,; p::AbstractProblem=problem)
return value(p, n.state);
end));
if (value(problem, neighbor.state) <= value(problem, current_node.state))
break;
end
current_node = neighbor;
end
return current_node.state;
end
"""
exp_schedule(;kvar::Int64=20, delta::Float64=0.005, lmt::Int64=100)
Return a scheduled time for simulated annealing.
"""
function exp_schedule(;kvar::Int64=20, delta::Float64=0.005, lmt::Int64=100)
return (function(t::Real; k=kvar, d=delta, limit=lmt)
return if_((t < limit), (k * exp(-d * t)), 0);
end);
end
"""
simulated_annealing(problem::T; schedule::Function=exp_schedule()) where {T <: AbstractProblem}
Return the solution node by applying the simulated annealing algorithm (Fig. 4.5) on the given
problem 'problem' and schedule function 'schedule'. If a solution node can't be found,
this function returns 'nothing' on failure.
"""
function simulated_annealing(problem::T; schedule::Function=exp_schedule()) where {T <: AbstractProblem}
local current_node = Node{typeof(problem.initial)}(problem.initial);
for t in 0:(typemax(Int64) - 1)
local temperature::Float64 = schedule(t);
if (temperature == 0)
return current_node;
end
local neighbors = expand(current_node, problem);
if (length(neighbors) == 0)
return current_node;
end
local next_node = rand(RandomDeviceInstance, neighbors);
delta_e = value(problem, next_node.state) - value(problem, current_node.state);
if ((delta_e > 0) || (exp(delta_e/temperature) > rand(RandomDeviceInstance)))
current_node = next_node;
end
end
return nothing;
end
#=
and_search() and or_search() are used by and_or_graph_search().
=#
function or_search(problem::T, state::AbstractVector, path::AbstractVector) where {T <: AbstractProblem}
if (goal_test(problem, state))
return [];
end
if (state in path)
return nothing;
end
for action in actions(problem, state)
local plan = and_search(get_result(problem, state, action), vcat(path, [state,]));
if (plan != nothing)
return [action, plan];
end
end
return nothing;
end
function or_search(problem::T, state::String, path::AbstractVector) where {T <: AbstractProblem}
if (goal_test(problem, state))
return [];
end
if (state in path)
return nothing;
end
for action in actions(problem, state)
local plan = and_search(problem, get_result(problem, state, action), vcat(path, [state,]));
if (plan != nothing)
return [action, plan];
end
end
return nothing;
end
function and_search(problem::T, states::AbstractVector, path::AbstractVector) where {T <: AbstractVector}
local plan = Dict{Any, Any}();
for state in states
plan[state] = or_search(problem, state, path);
if (plan[state] == nothing)
return nothing;
end
end