forked from aimacode/aima-julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logic.jl
1894 lines (1691 loc) · 68 KB
/
logic.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
using Printf
import Base: hash, ==, show;
export hash, ==, show,
Expression, expr, pretty_set,
variables, subexpressions, proposition_symbols,
parse_logic_definite_clause, is_logic_definite_clause, is_logic_symbol,
is_logic_variable, is_logic_variable_symbol, is_logic_proposition_symbol,
tt_entails, pl_true, tt_true,
to_conjunctive_normal_form,
eliminate_implications, move_not_inwards, distribute_and_over_or,
associate, dissociate, conjuncts, disjuncts,
AbstractKnowledgeBase, PropositionalKnowledgeBase, PropositionalDefiniteKnowledgeBase,
KnowledgeBaseAgentProgram,
make_percept_sentence, make_action_query, make_action_sentence, execute,
tell, ask, retract, clauses_with_premise,
pl_resolution, pl_resolve, pl_fc_entails,
inspect_literal, unit_clause_assign, find_unit_clause, find_pure_symbol,
dpll, dpll_satisfiable, walksat, HybridWumpusAgentProgram, plan_route,
translate_to_sat, extract_solution, sat_plan,
unify, occurrence_check, extend, substitute,
standardize_variables, fol_fc_ask,
FirstOrderLogicKnowledgeBase, fetch_rules_for_goal,
fol_bc_ask,
is_number, differentiate, simplify, differentiate_simplify,
constant_symbols, predicate_symbols;
abstract type AgentProgram end; #declare AgentProgram as a supertype for AgentProgram implementations
struct Expression
operator::String
arguments::Tuple
end
Expression(expression::Expression) = identity(expression)
Expression(op::String, args::Vararg{Any}) = Expression(op, map(Expression, args));
function (e::Expression)(args::Vararg{Any})
if ((length(e.arguments) == 0) && is_logic_symbol(e.operator))
return Expression(e.operator, map(Expression, args));
else
error("ExpressionError: ", e, " is not a Symbol (Nullary Expression)!");
end
end
# Hashing Expressions and n-Tuple of Expression(s).
hash(e::Expression, h::UInt) = xor(xor(hash(e.operator), hash(e.arguments)), h);
hash(t_e::Tuple{Vararg{Expression}}, h::UInt) = reduce(xor, vcat(map(hash, collect(t_e)), h));
# Julia does not allow for custom infix operators such as '==>', '<==', '<=>', etc.
# In addition, bitwise xor looks different between Julia ($/⊻) and Python (^).
==(e1::Expression, e2::Expression) = ((e1.operator == e2.operator) && (e1.arguments == e2.arguments));
function show(e::Expression)
if (length(e.arguments) == 0)
return e.operator;
elseif (is_logic_symbol(e.operator))
return @sprintf("%s(%s)", e.operator, join(map(show, map(Expression, e.arguments)), ", "));
elseif (length(e.arguments) == 1)
return @sprintf("%s(%s)", e.operator, show(Expression(e.arguments[1])));
else
return @sprintf("(%s)", join(map(show, map(Expression, map(string, e.arguments))), @sprintf(" %s ", e.operator)));
end
end
function show(io::IO, e::Expression)
print(io, show(e));
nothing;
end
abstract type AbstractKnowledgeBase end;
function tell(kb::T, e::Expression) where {T <: AbstractKnowledgeBase}
println("tell() is not implemented yet for ", typeof(kb), "!");
nothing;
end
function ask(kb::T, e::Expression) where {T <: AbstractKnowledgeBase}
println("ask() is not implemented yet for ", typeof(kb), "!");
nothing;
end
function retract(kb::T, e::Expression) where {T <: AbstractKnowledgeBase}
println("retract() is not implemented yet for ", typeof(kb), "!");
nothing;
end
#=
PropositionalKnowledgeBase is a knowledge base of propositional logic.
=#
struct PropositionalKnowledgeBase <: AbstractKnowledgeBase
clauses::Array{Expression, 1}
function PropositionalKnowledgeBase()
return new(Array{Expression, 1}([]));
end
function PropositionalKnowledgeBase(e::Expression)
local pkb = new(Array{Expression, 1}([]));
tell(pkb, e);
return pkb;
end
end
function tell(kb::PropositionalKnowledgeBase, e::Expression)
append!(kb.clauses, conjuncts(to_conjunctive_normal_form(e)));
nothing;
end
function ask(kb::PropositionalKnowledgeBase, e::Expression)
if (tt_entails(Expression("&", kb.clauses...,), e))
return Dict([]);
else
return false;
end
end
function retract(kb::PropositionalKnowledgeBase, e::Expression)
for conjunct in conjuncts(to_conjunctive_normal_form(e))
if (conjunct in kb.clauses)
for (index, item) in enumerate(kb.clauses)
if (item == conjunct)
deleteat!(kb.clauses, index);
break;
end
end
end
end
nothing;
end
#=
FirstOrderLogicKnowledgeBase is a knowledge base that contains first order
logic definite clauses.
=#
struct FirstOrderLogicKnowledgeBase <: AbstractKnowledgeBase
clauses::Array{Expression, 1}
function FirstOrderLogicKnowledgeBase()
return new(Array{Expression, 1}());
end
function FirstOrderLogicKnowledgeBase(initial_clauses::Array{Expression, 1})
local fol_kb = new(Array{Expression, 1}());
for clause in initial_clauses
tell(fol_kb, clause);
end
return fol_kb;
end
end
function tell(kb::FirstOrderLogicKnowledgeBase, e::Expression)
if (is_logic_definite_clause(e))
push!(kb.clauses, e);
else
error("tell(): ", repr(e), " is not a definite clause!");
end
nothing;
end
function ask(kb::FirstOrderLogicKnowledgeBase, e::Expression)
return fol_bc_ask(kb, e);
end
function retract(kb::FirstOrderLogicKnowledgeBase, e::Expression)
for (index, item) in enumerate(kb.clauses)
if (item == e)
deleteat!(kb.clauses, index);
break;
end
end
nothing;
end
function fetch_rules_for_goal(kb::FirstOrderLogicKnowledgeBase, goal::Expression)
return kb.clauses;
end
#=
KnowledgeBaseAgentProgram is a generic knowledge-based implementation of AgentProgram (Fig 7.1).
=#
mutable struct KnowledgeBaseAgentProgram <: AgentProgram
isTracing::Bool
knowledge_base::AbstractKnowledgeBase
t::UInt64
function KnowledgeBaseAgentProgram(kb::T; trace::Bool=false) where {T <: AbstractKnowledgeBase}
return new(trace, kb, UInt64(0));
end
end
function make_percept_sentence(percept::Expression, t::UInt64)
return Expression("Percept")(percept, Expression(dec(t)));
end
function make_action_query(t::UInt64)
return Expression(@sprintf("ShouldDo(action, %s)", dec(t)));
end
function make_action_sentence(action::Dict, t::UInt64)
return Expression("Did")(action[Expression("action")], Expression(dec(t)));
end
function execute(ap::KnowledgeBaseAgentProgram, percept::Expression)
tell(ap.knowledge_base, make_percept_sentence(percept, ap.t));
action = ask(ap.knowledge_base, make_action_query(ap.t));
tell(ap.knowledge_base, make_action_sentence(action, ap.t));
ap.t = ap.t + 1;
if (ap.isTracing)
@printf("%s perceives %s and does %s\n", string(typeof(ap)), repr(percept), string(action));
end
return action;
end
#=
PropositionalDefiniteKnowledgeBase is a knowledge base of propositional definite clause logic.
=#
struct PropositionalDefiniteKnowledgeBase <: AbstractKnowledgeBase
clauses::Array{Expression, 1}
function PropositionalDefiniteKnowledgeBase()
return new(Array{Expression, 1}([]));
end
function PropositionalDefiniteKnowledgeBase(e::Expression)
local pkb = new(Array{Expression, 1}([]));
tell(pkb, e);
return pkb;
end
end
function tell(kb::PropositionalDefiniteKnowledgeBase, e::Expression)
push!(kb.clauses, e);
nothing;
end
function ask(kb::PropositionalDefiniteKnowledgeBase, e::Expression)
if (pl_fc_entails(Expression("&", kb.clauses...,), e))
return Dict([]);
else
return false;
end
end
function retract(kb::PropositionalDefiniteKnowledgeBase, e::Expression)
for (index, item) in enumerate(kb.clauses)
if (item == e)
deleteat!(kb.clauses, index);
break;
end
end
nothing;
end
function clauses_with_premise(kb::PropositionalDefiniteKnowledgeBase, p::Expression)
return collect(c for c in kb.clauses if ((c.operator == "==>") && (p in conjuncts(c.arguments[1]))));
end
"""
pl_fc_entails(kb, q)
Apply the forward-chaining algorithm (Fig. 7.15) for propositional logic.
Return true or false based on whether PropositionalKnowledgeBase 'kb' entails
the proposition symbol 'q'.
"""
function pl_fc_entails(kb::PropositionalDefiniteKnowledgeBase, q::Expression)
local count::Dict = Dict(collect(Pair(c, length(conjuncts(c.arguments[1]))) for c in kb.clauses if (c.operator == "==>")));
local agenda::AbstractVector = collect(s for s in kb.clauses if (is_logic_proposition_symbol(s.operator)));
local inferred::Dict = Dict{Expression, Bool}();
while (length(agenda) != 0)
p = popfirst!(agenda);
if (p == q)
return true;
end
if (!(get(inferred, p, false)))
inferred[p] = true;
for c in clauses_with_premise(kb, p)
count[c] = count[c] - 1;
if (count[c] == 0)
push!(agenda, c.arguments[2])
end
end
end
end
return false;
end
function find_pure_symbol(symbols::Array{Expression, 1}, clauses::Array{Expression, 1})
for symbol in symbols
found_positive = false;
found_negative = false;
for clause in clauses
disjuncts_clause = disjuncts(clause);
if (!found_positive && (symbol in disjuncts_clause))
found_positive = true;
end
if (!found_negative && (Expression("~", symbol) in disjuncts_clause))
found_negative = true;
end
end
if (found_positive != found_negative)
return symbol, found_positive;
end
end
return nothing, nothing;
end
function inspect_literal(e::Expression)
if (e.operator == "~")
return e.arguments[1], false;
else
return e, true;
end
end
function unit_clause_assign(clause::Expression, model::Dict)
P = nothing;
value = nothing;
for literal in disjuncts(clause)
symbol, positive = inspect_literal(literal);
if (haskey(model, symbol))
if (model[symbol] == positive)
return nothing, nothing;
end
elseif (!(typeof(P) <: Nothing))
return nothing, nothing;
else
P = symbol;
value = positive;
end
end
return P, value;
end
function find_unit_clause(clauses::Array{Expression, 1}, model::Dict)
for clause in clauses
P, value = unit_clause_assign(clause, model);
if (!(typeof(P) <: Nothing))
return P, value;
end
end
return nothing, nothing;
end
function dpll(clauses::Array{Expression, 1}, symbols::Array{Expression, 1}, model::Dict)
local unknown_clauses::Array{Expression, 1} = Array{Expression, 1}();
for clause in clauses
val = pl_true(clause, model=model);
if (val == false)
return false;
end
if (val != true)
push!(unknown_clauses, clause);
end
end
if (length(unknown_clauses) == 0)
return model;
end
P, value = find_pure_symbol(symbols, unknown_clauses);
if (!(typeof(P) <: Nothing))
return dpll(clauses, removeall(symbols, P), extend(model, P, value));
end
P, value = find_unit_clause(clauses, model);
if (!(typeof(P) <: Nothing))
return dpll(clauses, removeall(symbols, P), extend(model, P, value));
end
P, symbols = symbols[1], symbols[2:end];
first_recursive_call = dpll(clauses, symbols, extend(model, P, true));
second_recursive_call = dpll(clauses, symbols, extend(model, P, false));
if (typeof(first_recursive_call) <: Dict)
return first_recursive_call;
elseif (typeof(first_recursive_call) <: Dict)
return second_recursive_call;
else
return false;
end
end
"""
dpll_satisfiable(s)
Use the Davis-Putnam-Logemann-Loveland (DPLL) algorithm (Fig. 7.17) to check satisfiability
of the given propositional logic sentence 's' and return the model (dictionary of truth value
assignments) if the sentence 's' is satisfiable and false otherwise.
"""
function dpll_satisfiable(s::Expression)
local clauses = conjuncts(to_conjunctive_normal_form(s));
local symbols = proposition_symbols(s);
return dpll(clauses, symbols, Dict());
end
"""
walksat(clauses)
Apply the WalkSAT algorithm (Fig. 7.18) to the given 'clauses'. walksat() will return a model
that satisfies the clauses if possible and returns 'nothing' on failure.
"""
function walksat(clauses::Array{Expression, 1}; p::Float64=0.5, max_flips::Int64=10000)
local symbols::Set{Expression} = Set{Expression}(reduce(vcat,
collect(collect(symbol for symbol in proposition_symbols(clause))
for clause in clauses)));
local model::Dict{Expression, Bool} = Dict(collect(Pair(symbol, rand(RandomDeviceInstance, [true, false]))
for symbol in symbols));
for i in 1:max_flips
satisfied = Array{Expression, 1}();
unsatisfied = Array{Expression, 1}();
for clause in clauses
push!(if_(pl_true(clause, model=model), satisfied, unsatisfied), clause);
end
if (length(unsatisfied) == 0)
return model;
end
clause = rand(RandomDeviceInstance, unsatisfied);
if (p > rand(RandomDeviceInstance))
symbol = rand(RandomDeviceInstance, proposition_symbols(clause));
else
symbol = argmax(proposition_symbols(clause),
(function(e)
model[e] = !model[e];
count = length((collect(c for c in clauses if (pl_true(c, model=model)))));
model[e] = !model[e];
return count;
end));
end
model[symbol] = !model[symbol];
end
nothing;
end
#=
HybridWumpusAgentProgram is a hybrid Wumpus implementation of AgentProgram (Fig. 7.20).
=#
mutable struct HybridWumpusAgentProgram <: AgentProgram
isTracing::Bool
kb::AbstractKnowledgeBase
t::UInt64
plan::AbstractVector
function HybridWumpusAgentProgram(kb::T; trace::Bool=false) where {T <: AbstractKnowledgeBase}
return new(trace, kb, UInt64(0), []);
end
end
function plan_route(current, goals, allowed)
println("plan_route() is not implemented yet!");
nothing;
end
function execute(ap::HybridWumpusAgentProgram, percept::AbstractVector)
println("execute() is not implemented yet for HybridWumpusAgentProgram!");
nothing;
end
function translate_to_sat(initial::T, transition::Dict, goal::T, time::Int64, state_dict::Dict, action_dict::Dict) where T
local clauses::Array{Expression, 1} = Array{Expression, 1}();
local states::AbstractVector = collect(keys(transition));
local state_count_iterator = Base.Iterators.countfrom();
local state_number::Int64 = -1;
for state in states
for t in 0:time
state_number = iterate(state_count_iterator, state_number)[2];
state_dict[(state, t)] = Expression(@sprintf("State_%lli", state_number));
end
end
push!(clauses, state_dict[(initial, 0)]);
push!(clauses, state_dict[(goal, time)]);
local transition_count_iterator = Base.Iterators.countfrom();
local transition_number = -1;
for state in states
for action in keys(transition[state])
state_val_key = transition[state][action];
for t in 0:(time - 1)
transition_number = iterate(transition_count_iterator, transition_number)[2];
action_dict[(state, action, t)] = Expression(@sprintf("Transition_%lli", transition_number));
push!(clauses, Expression("==>", action_dict[(state, action, t)], state_dict[(state, t)]));
push!(clauses, Expression("==>", action_dict[(state, action, t)], state_dict[(state_val_key, (t + 1))]));
end
end
end
for t in 0:time
push!(clauses, associate("|", Tuple((collect(state_dict[(state, t)] for state in states)...,))));
for (i, state) in enumerate(states)
for state_val_key in states[(i+1):end]
push!(clauses, Expression("|",
Expression("~", state_dict[(state, t)]),
Expression("~", state_dict[(state_val_key, t)])));
end
end
end
for t in 0:(time - 1)
local transitions_t::AbstractVector = collect(transition_t for transition_t in keys(action_dict) if (transition_t[3] == t));
push!(clauses, associate("|", Tuple((collect(action_dict[transition_t] for transition_t in transitions_t)...,))));
for (i, transition_t) in enumerate(transitions_t)
for transition_t_alternative in transitions_t[(i + 1):end]
push!(clauses, Expression("|",
Expression("~", action_dict[transition_t]),
Expression("~", action_dict[transition_t_alternative])));
end
end
end
return associate("&", Tuple((clauses...,)));
end
function extract_solution(model::Dict, action_dict::Dict)
# Collect transitions that are true in the SAT 'model' solution.
local transitions::AbstractVector = collect(transition for transition in keys(action_dict) if (model[action_dict[transition]]));
sort!(transitions, lt=(function(t1, t2)
return isless(t1[3], t2[3]);
end));
return collect(action for (state, action, time) in transitions);
end
"""
sat_plan(initial, transition, goal, t_max)
Apply the SATPlan algorithm (Fig. 7.22) to the given planning problem, returning a solution or 'nothing'
when the algorithm fails. The planning problem is converted to conjunctive normal form logic sentence in
order to be solved as a satisfication problem.
The 'initial' and 'goal' states should have the same type.
"""
function sat_plan(initial::T, transition::Dict, goal::T, t_max::Int64; sat_solver::Function=dpll_satisfiable) where T
local states::Dict = Dict();
local actions::Dict = Dict();
for t in 0:(t_max - 1)
empty!(states);
empty!(actions);
local cnf::Expression = translate_to_sat(initial, transition, goal, t, states, actions);
local model = sat_solver(cnf);
if (model != false)
return extract_solution(model, actions);
end
end
nothing;
end
function is_logic_symbol(s::String)
if (length(s) == 0)
return false;
else
return isletter(s[1]);
end
end
function is_logic_variable_symbol(s::String)
return (is_logic_symbol(s) && islowercase(s[1]));
end
function is_logic_variable(e::Expression)
return ((length(e.arguments) == 0) && islowercase(e.operator[1]))
end
"""
is_logic_proposition_symbol(s)
Return if the given 's' is an initial uppercase String that is not 'TRUE' or 'FALSE'.
"""
function is_logic_proposition_symbol(s::String)
return (is_logic_symbol(s) && isuppercase(s[1]) && (s != "TRUE") && (s != "FALSE"));
end
#=
The Python implementation of expr() uses of eval() and overloaded binary/unary infix
operators to evaluate a String as an Expression.
This Julia implementation of expr() parses the given String into an expression tree of
tokens, before returning the parsed Expression.
Consecutive operators should be delimited with with a space or parentheses.
=#
"""
expr(s::String)
Parse the given String as an Expression and return the parsed Expression.
"""
function expr(s::String)
local tokens::AbstractVector = identify_tokens(s);
tokens = parenthesize_tokens(tokens);
tokens = parenthesize_arguments(tokens);
local root_node::ExpressionNode = construct_expression_tree(tokens);
root_node = prune_nodes(root_node);
return evaluate_expression_tree(root_node);
end
function expr(e::Expression)
return e;
end
function subexpressions(e::Expression)
local answer::AbstractVector = [e];
for arg in e.arguments
answer = vcat(answer, subexpressions(arg));
end
return answer;
end
function subexpressions(e::Int)
local answer::AbstractVector = [Expression(string(e))];
return answer;
end
function variables(e::Expression)
return Set(x for x in subexpressions(e) if is_logic_variable(x));
end
function proposition_symbols(e::Expression)
if (is_logic_proposition_symbol(e.operator))
return [e];
else
symbols::Set{Expression} = Set{Expression}();
for argument in e.arguments
argument_symbols = proposition_symbols(argument);
for symbol in argument_symbols
push!(symbols, symbol);
end
end
return collect(symbols);
end
end
function is_logic_definite_clause(e::Expression)
if (is_logic_symbol(e.operator))
return true;
elseif (e.operator == "==>")
antecedent, consequent = e.arguments;
return (is_logic_symbol(consequent.operator) &&
all(collect(is_logic_symbol(arg.operator) for arg in conjuncts(antecedent))));
else
return false;
end
end
function parse_logic_definite_clause(e::Expression)
if (!is_logic_definite_clause(e))
error("parse_logic_definite_clause: The expression given is not a definite clause!");
else
if (is_logic_symbol(e.operator))
return Array{Expression, 1}([]), e;
else
antecedent, consequent = e.arguments;
return conjuncts(antecedent), consequent;
end
end
end
"""
tt_entails(kb::Expression, alpha::Expression)
Use the truth-table enumeration algorithm (Fig. 7.10) on the sentence 'alpha'
and a conjunction of clauses 'kb'. Return true or false based on whether 'kb' entails
'alpha'.
"""
function tt_entails(kb::Expression, alpha::Expression)
if (length(variables(alpha)) != 0)
error("tt_entails(): Found logic variables in 'alpha' Expression!");
end
return tt_check_all(kb, alpha, proposition_symbols(Expression("&", kb, alpha)), Dict());
end
function tt_check_all(kb::Expression, alpha::Expression, symbols::AbstractVector, model::Dict)
if (length(symbols) == 0)
eval_kb = pl_true(kb, model=model)
if (typeof(eval_kb) <: Nothing)
return true;
elseif (eval_kb == false)
return true;
else
result = pl_true(alpha, model=model);
if (typeof(result) <: Bool)
return result;
else
error("tt_check_all(): pl_true() returned an unexpected ", typeof(result), " type!");
end
end
else
P = symbols[1];
rest::AbstractVector = symbols[2:end];
return (tt_check_all(kb, alpha, rest, extend(model, P, true)) &&
tt_check_all(kb, alpha, rest, extend(model, P, false)));
end
end
function tt_true(alpha::Expression)
return tt_entails(Expression("TRUE"), alpha);
end
function tt_true(alpha::String)
return tt_entails(Expression("TRUE"), expr(alpha));
end
function pl_true(e::Expression; model::Dict=Dict())
if (e == Expression("TRUE"))
return true;
elseif (e == Expression("FALSE"))
return false;
elseif (is_logic_proposition_symbol(e.operator))
return get(model, e, nothing);
elseif (e.operator == "~")
subexpression = pl_true(e.arguments[1], model=model);
if (typeof(subexpression) <: Nothing)
return nothing;
else
return !subexpression;
end
elseif (e.operator == "|")
result = false;
for argument in e.arguments
subexpression = pl_true(argument, model=model);
if (subexpression == true)
return true;
end
if (typeof(subexpression) <: Nothing)
result = nothing;
end
end
return result;
elseif (e.operator == "&")
result = true;
for argument in e.arguments
subexpression = pl_true(argument, model=model);
if (subexpression == false)
return false;
end
if (typeof(subexpression) <: Nothing)
result = nothing;
end
end
return result;
end
local p::Expression;
local q::Expression;
if (length(e.arguments) == 2)
p, q = e.arguments;
else
error("PropositionalLogicError: Expected 2 arguments in expression ", repr(e),
" got ", length(e.arguments), " arguments!");
end
if (e.operator == "==>")
return pl_true(Expression("|", Expression("~", p), q), model=model);
elseif (e.operator == "<==")
return pl_true(Expression("|", p, Expression("~", q)), model=model);
end;
p_t = pl_true(p, model=model);
if (typeof(p_t) <: Nothing)
return nothing;
end
q_t = pl_true(q, model=model);
if (typeof(q_t) <: Nothing)
return nothing;
end
if (e.operator == "<=>")
return p_t == q_t;
elseif (e.operator == "^")
return p_t != q_t;
else
error("PropositionalLogicError: Illegal operator detected in expression ", repr(e), "!")
end
end
"""
eliminate_implications(e)
Eliminate any implications in the given Expression by using the definition of biconditional introduction,
material implication, and converse implication with De Morgan's Laws and return the modified Expression.
"""
function eliminate_implications(e::Expression)
if ((length(e.arguments) == 0) || is_logic_symbol(e.operator))
return e;
end
local arguments = map(eliminate_implications, e.arguments);
local a::Expression = first(arguments);
local b::Expression = last(arguments);
if (e.operator == "==>")
return Expression("|", b, Expression("~", a));
elseif (e.operator == "<==")
return Expression("|", a, Expression("~", b));
elseif (e.operator == "<=>")
return Expression("&", Expression("|", a, Expression("~", b)), Expression("|", b, Expression("~", a)));
elseif (e.operator == "^")
if (length(arguments) != 2)
#If the length of 'arguments' is 1, last(arguments)
#gives us the same Expression for 'b' as 'a'.
error("EliminateImplicationsError: XOR should be applied to 2 arguments, found ",
length(arguments), " arguments!");
end
return Expression("|", Expression("&", a, Expression("~", b)), Expression("&", Expression("~", a), b));
else
if (!(e.operator in ("&", "|", "~")))
error("EliminateImplicationsError: Found an unexpected operator '", e.operator, "'!");
end
return Expression(e.operator, arguments...,);
end
end
function move_not_inwards_negate_argument(e::Expression)
return move_not_inwards(Expression("~", e));
end
"""
move_not_inwards(e)
Apply De Morgan's laws to the given Expression and return the modified Expression.
"""
function move_not_inwards(e::Expression)
if (e.operator == "~")
local a::Expression = e.arguments[1];
if (a.operator == "~")
return move_not_inwards(a.arguments[1]);
elseif (a.operator == "&")
return associate("|", map(move_not_inwards_negate_argument, a.arguments));
elseif (a.operator == "|")
return associate("&", map(move_not_inwards_negate_argument, a.arguments));
else
return e;
end
elseif (is_logic_symbol(e.operator) || (length(e.arguments) == 0))
return e;
else
return Expression(e.operator, map(move_not_inwards, e.arguments)...,);
end
end
function distribute_and_over_or(e::Expression)
if (e.operator == "|")
local a::Expression = associate("|", e.arguments);
if (a.operator != "|")
return distribute_and_over_or(a);
elseif (length(a.arguments) == 0)
return Expression("FALSE");
elseif (length(a.arguments) == 1)
return distribute_and_over_or(a.arguments[1]);
end
conjunction = findfirst((function(arg)
return (arg.operator == "&");
end), a.arguments);
if (conjunction === nothing) #(&) operator was not found in a.arguments
return a;
else
conjunction = a.arguments[conjunction];
end
others = Tuple((collect(a for a in a.arguments if (!(a == conjunction)))...,));
rest = associate("|", others);
return associate("&", Tuple((collect(distribute_and_over_or(Expression("|", conjunction_arg, rest))
for conjunction_arg in conjunction.arguments)...,)));
elseif (e.operator == "&")
return associate("&", map(distribute_and_over_or, e.arguments));
else
return e;
end
end
function expand_prefix_nary_expression(operator::String, arguments::AbstractVector)
if (length(arguments) == 1)
return arguments[1];
else
current = first(arguments);
rest = arguments[2:end];
return Expression(operator, current, expand_prefix_nary_expression(operator, rest));
end
end
function associate(operator::String, arguments::Tuple)
dissociated_arguments = dissociate(operator, arguments);
if (length(dissociated_arguments) == 0)
if (operator == "&")
return Expression("TRUE");
elseif (operator == "|")
return Expression("FALSE");
elseif (operator == "+")
return Expression("0");
elseif (operator == "*")
return Expression("1");
else
error("AssociateError: Found unexpected operator '", operator, "'!");
end
elseif (length(dissociated_arguments) == 1)
return dissociated_arguments[1];
else
return Expression(operator, Tuple((dissociated_arguments...,)));
end
end
function dissociate_collect(operator::String, arguments::Tuple{Vararg{Expression}}, result_array::AbstractVector)
for argument in arguments
if (argument.operator == operator)
dissociate_collect(operator, argument.arguments, result_array);
else
push!(result_array, argument);
end
end
nothing;
end
function dissociate(operator::String, arguments::Tuple{Vararg{Expression}})
local result = Array{Expression, 1}([]);
dissociate_collect(operator, arguments, result);
return result;
end
function conjuncts(e::Expression)
return dissociate("&", (e,));
end
function disjuncts(e::Expression)
return dissociate("|", (e,));
end
"""
to_conjunctive_normal_form(s)
Convert the given propositional logical sentence 's' to its equivalent
conjunctive normal form.
"""
function to_conjunctive_normal_form(sentence::Expression)
return distribute_and_over_or(move_not_inwards(eliminate_implications(sentence)));
end
function to_conjunctive_normal_form(sentence::String)
return distribute_and_over_or(move_not_inwards(eliminate_implications(expr(sentence))));
end
function pl_resolve(c_i::Expression, c_j::Expression)
local clauses = Array{Expression, 1}([]);
for d_i in disjuncts(c_i)
for d_j in disjuncts(c_j)
if ((d_i == Expression("~", d_j)) || (Expression("~", d_i) == d_j))
d_new = Tuple((collect(Set{Expression}(append!(removeall(disjuncts(c_i), d_i), removeall(disjuncts(c_j), d_j))))...,));
push!(clauses, associate("|", d_new));
end
end
end
return clauses;
end
"""
pl_resolution(kb, alpha)
Apply a simple propositional logic resolution algorithm (Fig. 7.12) on the given knowledge base
and propositional logic sentence (query). Return a boolean indicating if the sentence follows
the clauses that exist in the given knowledge base.
"""
function pl_resolution(kb::T, alpha::Expression) where {T <: AbstractKnowledgeBase}
local clauses::AbstractVector = append!(copy(kb.clauses), conjuncts(to_conjunctive_normal_form(Expression("~", alpha))));
local new_set = Set{Expression}();
while (true)
n = length(clauses);
pairs = collect((clauses[i], clauses[j]) for i in 1:n for j in i+1:n);
for (c_i, c_j) in pairs
local resolvents = pl_resolve(c_i, c_j);
if (Expression("FALSE") in resolvents)
return true;
end
union!(new_set, Set{Expression}(resolvents));
end
if (issubset(new_set, Set{Expression}(clauses)))
return false;
end
for c in new_set
if (!(c in clauses))
push!(clauses, c);
end
end
end
end
function occurrence_check(key, x, substitutions::Dict)
if (key == x)
println("occurrence_check(::Any, ::Any, ::Dict) returned true!!!");
return true;
else
return false;
end
end
function occurrence_check(key::Expression, x::T, substitutions::Dict) where {T <: Union{Tuple, Vector}}
if (key == x)
println("occurrence_check(::Expression, ::Union{Tuple, Vector}, ::Dict) returned true!!!");