-
Notifications
You must be signed in to change notification settings - Fork 2
/
actions.py
2118 lines (1595 loc) · 65 KB
/
actions.py
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
from parse_en import *
from nl_to_fol import *
import sys
sys.path.insert(0, "../logic")
from logic.logic import *
from phidias.Types import *
import configparser
import math
import time
from datetime import datetime
from difflib import SequenceMatcher
from lkb_manager import *
config = configparser.ConfigParser()
config.read('config.ini')
cnt = itertools.count(1)
dav = itertools.count(1)
VERBOSE = config.getboolean('NL_TO_FOL', 'VERBOSE')
LANGUAGE = config.get('NL_TO_FOL', 'LANGUAGE')
CONDITIONAL_WORDS = str(config.get('NL_TO_FOL', 'CONDITIONAL_WORDS')).split(", ")
ASSIGN_RULES_ADMITTED = config.getboolean('NL_TO_FOL', 'ASSIGN_RULES_ADMITTED')
LEMMATIZATION = config.getboolean('NL_TO_FOL', 'LEMMATIZATION')
WAIT_TIME = config.getint('AGENT', 'WAIT_TIME')
LOG_ACTIVE = config.getboolean('AGENT', 'LOG_ACTIVE')
FILE_KB_NAME = config.get('AGENT', 'FILE_KB_NAME')
FILE_EXPORT_LKB_NAME = config.get('AGENT', 'FILE_EXPORT_LKB_NAME')
INCLUDE_ACT_POS = config.getboolean('POS', 'INCLUDE_ACT_POS')
INCLUDE_NOUNS_POS = config.getboolean('POS', 'INCLUDE_NOUNS_POS')
INCLUDE_ADJ_POS = config.getboolean('POS', 'INCLUDE_ADJ_POS')
INCLUDE_PRP_POS = config.getboolean('POS', 'INCLUDE_PRP_POS')
INCLUDE_ADV_POS = config.getboolean('POS', 'INCLUDE_ADV_POS')
OBJ_JJ_TO_NOUN = config.getboolean('POS', 'OBJ_JJ_TO_NOUN')
GEN_PREP = config.getboolean('GEN', 'GEN_PREP')
GEN_ADJ = config.getboolean('GEN', 'GEN_ADJ')
GEN_ADV = config.getboolean('GEN', 'GEN_ADV')
GEN_EXTRA = config.getboolean('GEN', 'GEN_EXTRA')
GEN_EXTRA_POS = config.get('GEN', 'EXTRA_GEN_POS').split(", ")
HOST = config.get('LKB', 'HOST')
USER = config.get('LKB', 'USER')
PASSWORD = config.get('LKB', 'PASSWORD')
LKB_USAGE = config.getboolean('LKB', 'LKB_USAGE')
MIN_CONFIDENCE = config.getfloat('LKB', 'MIN_CONFIDENCE')
EMPTY_HKB_AFTER_REASONING = config.getboolean('LKB', 'EMPTY_HKB_AFTER_REASONING')
NESTED_REASONING = config.getboolean('REASONING', 'NESTED_REASONING')
LOC_PREPS = str(config.get('QA', 'LOC_PREPS')).split(", ")
TIME_PREPS = str(config.get('QA', 'TIME_PREPS')).split(", ")
COP_VERB = str(config.get('QA', 'COP_VERB')).split(", ")
ROOT_TENSE_DEBT = str(config.get('QA', 'ROOT_TENSE_DEBT')).split(", ")
SHOW_REL = config.getboolean('QA', 'SHOW_REL')
# creating debt tenses dictionary
tense_debt_voc = {}
for rtd in ROOT_TENSE_DEBT:
couple = rtd.split(":")
tense_debt_voc.update({couple[0]: couple[1]})
parser = Parse(VERBOSE)
fol_manager = ManageFols(VERBOSE, LANGUAGE)
# Clauses Knowledge Base instantion
kb_fol = FolKB([])
# Lower Knowledge Base Manager
lkbm = ManageLKB(HOST, USER, PASSWORD)
# Telegram bot
BOT = None
# FOl Reasoning procedures
class aggr_adj(Procedure): pass
class aggr_adv(Procedure): pass
class aggr_nouns(Procedure): pass
class mod_to_gnd(Procedure): pass
class gnd_prep_obj(Procedure): pass
class prep_to_gnd(Procedure): pass
class finalize_clause(Procedure): pass
class parse(Procedure): pass
class process_clause(Procedure): pass
class finalize_gnd(Procedure): pass
class apply_adv(Procedure): pass
class actions_to_clauses(Procedure): pass
class gnd_actions(Procedure): pass
class new_def_clause(Procedure): pass
class process_rule(Procedure): pass
# Reactive procedures - direct commands
class parse_command(Procedure): pass
class aggr_entities(Procedure): pass
class produce_intent(Procedure): pass
class produce_mod(Procedure): pass
# Reactive procedures - routines
class parse_routine(Procedure): pass
class produce_conds(Procedure): pass
class aggr_ent_conds(Procedure): pass
class produce_mod_conds(Procedure): pass
class produce_routine(Procedure): pass
class aggr_ent_rt(Procedure): pass
class produce_mod_rt(Procedure): pass
# check for routines execution
class check_conds(Procedure): pass
# start agent command
class go(Procedure): pass
# STT Front-End procedures
class hkb(Procedure): pass
class lkb(Procedure): pass
class flush(Procedure): pass
class manage_msg(Procedure): pass
class proc(Procedure): pass
# initialize Clauses Kbs
class chkb(Procedure): pass
class clkb(Procedure): pass
# auto feed procedure from file
class feed(Procedure): pass
class make_feed(Procedure): pass
# export lkb in a file excel
class expt(Procedure): pass
# mode reactors
class HOTWORD_DETECTED(Reactor): pass
class STT(Belief): pass
class WAKE(Belief): pass
class LISTEN(Belief): pass
class REASON(Belief): pass
class RETRACT(Belief): pass
class IS_RULE(Belief): pass
class WAIT(Belief): pass
class TEST(Belief): pass
# domotic reactive routines
class r1(Procedure): pass
class r2(Procedure): pass
# domotic direct commands
class d1(Procedure): pass
class d2(Procedure): pass
# domotic sensor simulatons
class s1(Procedure): pass
class s2(Procedure): pass
# normal requests beliefs
class GROUND(Belief): pass
class PRE_MOD(Belief): pass
class MOD(Belief): pass
class PRE_INTENT(Belief): pass
class INTENT(Reactor): pass
# routines beliefs
class PRE_ROUTINE(Belief): pass
class ROUTINE(Belief): pass
class ROUTINE_PRE_MOD(Belief): pass
class ROUTINE_MOD(Belief): pass
class ROUTINE_GROUND(Belief): pass
# conditionals beliefs
class PRE_COND(Belief): pass
class COND(Belief): pass
class COND_GROUND(Belief): pass
class COND_PRE_MOD(Belief): pass
class SENSOR(Belief): pass
class START_ROUTINE(Reactor): pass
# Chatbot beliefs
class OUT(Reactor): pass
class MSG(Belief): pass
class CHAT_ID(Belief): pass
# clause
class CLAUSE(Belief): pass
# action
class ACTION(Belief): pass
# preposition
class PREP(Belief): pass
# ground
class GND(Belief): pass
# adverb
class ADV(Belief): pass
# adjective
class ADJ(Belief): pass
# left clause
class LEFT_CLAUSE(Belief): pass
# definite clause
class DEF_CLAUSE(Belief): pass
# remain
class REMAIN(Belief): pass
# preposition accumlator
class PRE_CROSS(Belief): pass
# Modificators number
class GEN_MASK(Belief): pass
# Actions crossing var
class ACT_CROSS_VAR(Belief): pass
# parse rule beliefs
class DEP(Belief): pass
class MST_ACT(Belief): pass
class MST_VAR(Belief): pass
class MST_PREP(Belief): pass
class MST_BIND(Belief): pass
class MST_COMP(Belief): pass
class MST_COND(Belief): pass
class parse_deps(Procedure): pass
class feed_mst(Procedure): pass
# Question Answering beliefs
class SEQ(Belief): pass
class CAND(Belief): pass
class ANSWERED(Belief): pass
class CASE(Belief): pass
class LOC_PREP(Belief): pass
class LP(Belief): pass
class TIME_PREP(Belief): pass
class ROOT(Belief): pass
class RELATED(Belief): pass
class feed_kbs(Action):
"""Feed Knowledge Bases from file"""
def execute(self):
try:
with open(FILE_KB_NAME) as f:
for line in f:
print(line)
self.assert_belief(TEST(line.rstrip()))
except IOError:
print("\nFile " + FILE_KB_NAME + " not found.")
class reset_ct(Action):
"""Reset execution time"""
def execute(self):
parser.set_start_time()
class log_op(Action):
"""log operations"""
def execute(self, *args):
a = str(args).split("'")
if LOG_ACTIVE:
with open("log.txt", "a") as myfile:
myfile.write("\n\n" + a[1])
class log_cmd(Action):
"""log direct assertions from keyboard"""
def execute(self, *args):
a = str(args).split("'")
if LOG_ACTIVE:
with open("log.txt", "a") as myfile:
myfile.write("\n\n" + a[1] + ": " + a[5])
class show_ct(Action):
"""Show execution time"""
def execute(self):
ct = parser.get_comp_time()
print("\nExecution time: ", ct)
if LOG_ACTIVE:
with open("log.txt", "a") as myfile:
myfile.write("\nExecution time: " + str(ct))
class set_wait(Action):
"""Set duration of the session from WAIT_TIME in config.ini [AGENT]"""
def execute(self):
self.assert_belief(WAIT(WAIT_TIME))
if LOG_ACTIVE:
with open("log.txt", "a") as myfile:
myfile.write("\n\n------ NEW SESSION ------ " + str(datetime.now().strftime("%d/%m/%Y %H:%M:%S")))
class eval_cls(ActiveBelief):
def evaluate(self, arg1):
utterance = str(arg1).split("'")[1]
bc_result = kb_fol.ask(expr(utterance))
print("\n ---- NOMINAL REASONING ---\n")
print("Result: " + str(bc_result))
if bc_result is False:
print("\n\n ---- NESTED REASONING ---")
candidates = []
nested_result = kb_fol.nested_ask(expr(utterance), candidates)
if nested_result is None:
return True
elif nested_result is False:
return False
else:
return True
else:
return True
class lemma_in_syn(ActiveBelief):
def evaluate(self, arg1, arg2):
verb = str(arg1).split("'")[3]
synset = str(arg2).split("'")[1]
pos = wordnet.VERB
syns = wordnet.synsets(verb, pos=pos, lang=LANGUAGE)
for syn in syns:
if syn.name() == synset:
return True
return False
class preprocess_clause(Action):
def execute(self, *args):
gen_mask = str(args[0]())
mode = str(args[1]())
type = str(args[2]())
print("\n--------- NEW DEFINITE CLAUSE ---------\n ")
print("gen_mask: " + gen_mask)
print("mode: " + mode)
print("type: " + type + "\n")
if mode == "ONE":
Gen_mode = False
else:
Gen_mode = True
self.MAIN_NEG_PRESENT = False
deps = parser.get_last_deps()
for i in range(len(deps)):
governor = self.get_lemma(deps[i][1]).capitalize() + ":" + self.get_pos(deps[i][1])
dependent = self.get_lemma(deps[i][2]).capitalize() + ":" + self.get_pos(deps[i][2])
deps[i] = [deps[i][0], governor, dependent]
print("\n" + str(deps))
MST = parser.get_last_MST()
print("\nMST: \n" + str(MST))
print("\nGMC_SUPP: \n" + str(parser.GMC_SUPP))
print("\nSUPP_SUPP_REV: \n" + str(parser.GMC_SUPP_REV))
print("\nLCD: \n" + str(parser.LCD))
# MST varlist correction on cases of adj-obj
if OBJ_JJ_TO_NOUN is True:
for v in MST[1]:
if self.get_pos(v[1]) in ['JJ', 'JJR', 'JJS']:
old_value = v[1]
new_value = self.get_lemma(v[1]) + ":NNP"
v[1] = new_value
new_value_clean = parser.get_lemma(new_value.lower())[:-2]
print("\nadj-obj correction...", new_value_clean)
# checking if the lemma has a disambiguation
if new_value_clean in parser.GMC_SUPP_REV:
parser.LCD[parser.GMC_SUPP_REV[new_value_clean]] = new_value_clean
# binds correction
for b in MST[3]:
if b[0] == old_value:
b[0] = new_value
m = ManageFols(VERBOSE, LANGUAGE)
vect_LR_fol = m.build_LR_fol(MST, 'e')
print("\nBefore dealing case:\n" + str(vect_LR_fol))
if len(vect_LR_fol) == 0:
print("\n --- IMPROPER VERBAL PHRASE COSTITUTION ---")
return
if type == "NOMINAL":
# NOMINAL CASE
CHECK_IMPLICATION = fol_manager.check_implication(vect_LR_fol)
if not CHECK_IMPLICATION:
if ASSIGN_RULES_ADMITTED:
check_isa = fol_manager.check_for_rule(deps, vect_LR_fol)
if check_isa:
self.assert_belief(IS_RULE("TRUE"))
dclause = vect_LR_fol[:]
else:
dclause = vect_LR_fol[:]
dclause[1] = ["==>"]
else:
# RULE CASE
ent_root = self.get_ent_ROOT(deps)
dav_rule = self.get_dav_rule(vect_LR_fol, ent_root)
positive_vect_LR_fol = []
for v in vect_LR_fol:
lemma = self.get_lemma(v[0])[:-2]
if self.check_neg(lemma, LANGUAGE) and v[1] == dav_rule:
self.assert_belief(RETRACT("ON"))
else:
positive_vect_LR_fol.append(v)
vect_LR_fol_plus_isa = fol_manager.build_isa_fol(positive_vect_LR_fol, deps)
dclause = fol_manager.isa_fol_to_clause(vect_LR_fol_plus_isa)
print("\nAfter dealing case:\n", dclause)
# IMPLICATION CASES
if dclause[1][0] == "==>":
mods = []
for v in dclause[2]:
if self.get_pos(v[0]) in GEN_EXTRA_POS and GEN_EXTRA is True:
mods.append(v[0])
if self.get_pos(v[0]) == "IN" and GEN_PREP is True:
mods.append(v[0])
elif self.get_pos(v[0]) in ['JJ', 'JJR', 'JJS'] and GEN_ADJ is True:
mods.append(v[0])
elif self.get_pos(v[0]) in ['RB', 'RBR', 'RBS']:
if GEN_ADV is True:
mods.append(v[0])
lemma = self.get_lemma(v[0])[:-2]
if self.check_neg(lemma, LANGUAGE):
print("\nNot a definite clause!")
return
if gen_mask == "BASE":
print("\nmods: " + str(mods))
nmods = int(math.pow(2, len(mods))) - 1
print("\ngereralizations number: " + str(nmods) + "\n")
actual_mask = ""
for i in range(len(mods)):
actual_mask = actual_mask + "0"
gen_mask = actual_mask
# creating dictionary
voc = {}
for i in range(len(mods)):
if gen_mask[i] == '1':
val = True
else:
val = False
voc.update({mods[i]: val})
# triggering generalizations production
if len(mods) > 0 and Gen_mode is True:
inc_mask = self.get_inc_mask(actual_mask)
self.assert_belief(GEN_MASK(inc_mask))
elif gen_mask == "FULL":
# creating dictionary
voc = {}
for i in range(len(mods)):
voc.update({mods[i]: True})
else:
# creating dictionary
voc = {}
full_true_voc = {}
for i in range(len(mods)):
if gen_mask[i] == '1':
val = True
else:
val = False
voc.update({mods[i]: val})
full_true_voc.update({mods[i]: True})
inc_mask = self.get_inc_mask(gen_mask)
if len(inc_mask) == len(gen_mask):
self.assert_belief(GEN_MASK(inc_mask))
print("\nPROCESSING LEFT HAND-SIDE...")
self.process_fol(dclause[0], "LEFT", voc)
print("\nPROCESSING RIGHT HAND-SIDE...")
self.process_fol(dclause[2], "RIGHT", voc)
# FLAT CASES
else:
mods = []
nomain_negs = []
main_neg_index = 0
ent_root = self.get_ent_ROOT(deps)
dav_act = self.get_dav_rule(dclause, ent_root)
for v in dclause:
if self.get_pos(v[0]) in GEN_EXTRA_POS and GEN_EXTRA is True:
mods.append(v[0])
elif self.get_pos(v[0]) == "IN" and GEN_PREP is True:
mods.append(v[0])
elif self.get_pos(v[0]) in ['JJ', 'JJR', 'JJS'] and GEN_ADJ is True:
mods.append(v[0])
if self.get_pos(v[0]) in ['RB', 'RBR', 'RBS']:
lemma = self.get_lemma(v[0])[:-2]
if self.check_neg(lemma, LANGUAGE):
if v[1] == dav_act:
self.MAIN_NEG_PRESENT = True
self.assert_belief(RETRACT("ON"))
main_neg_index = len(mods) - 1
dclause.remove(v)
else:
if GEN_ADV is True:
mods.append(v[0])
nomain_negs.append(v)
else:
if GEN_ADV is True:
mods.append(v[0])
# every verb/adj will carry its non-main negative
negs = {}
for n in nomain_negs:
for v in dclause:
if v[1] == n[1]:
if v not in nomain_negs:
negs.update({v[0]: n[0]})
# only reason
if gen_mask == "FULL":
# creating dictionary
voc = {}
for i in range(len(mods)):
voc.update({mods[i]: True})
elif gen_mask == "BASE":
actual_mask = ""
if self.MAIN_NEG_PRESENT:
for i in range(len(mods)):
if i == main_neg_index:
actual_mask = actual_mask + "0"
else:
actual_mask = actual_mask + "1"
else:
for i in range(len(mods)):
actual_mask = actual_mask + "0"
gen_mask = actual_mask
# creating vocabolary
voc = {}
for i in range(len(mods)):
if gen_mask[i] == '1':
val = True
else:
val = False
voc.update({mods[i]: val})
# voc rectification for carrying negations, other negations = True
for nm in nomain_negs:
voc[nm[0]] = True
for ng in negs:
if ng in voc:
voc[negs[ng]] = voc[ng]
nmods = int(math.pow(2, len(mods))) - 1
print("\ngereralizations number: " + str(nmods))
# triggering generalizations production
if len(mods) > 0 and Gen_mode and not self.MAIN_NEG_PRESENT:
inc_mask = self.get_inc_mask(actual_mask)
self.assert_belief(GEN_MASK(inc_mask))
else:
# creating vocabolary
voc = {}
for i in range(len(mods)):
if gen_mask[i] == '1':
val = True
else:
val = False
voc.update({mods[i]: val})
# voc rectification for carrying negations, other negations = True
for nm in nomain_negs:
voc[nm[0]] = True
for ng in negs:
if ng in voc:
voc[negs[ng]] = voc[ng]
inc_mask = self.get_inc_mask(gen_mask)
if len(inc_mask) == len(gen_mask):
self.assert_belief(GEN_MASK(inc_mask))
self.process_fol(dclause, "FLAT", voc)
def get_ent_ROOT(self, deps):
for d in deps:
if d[0] == "ROOT":
return d[1]
def get_dav_rule(self, fol, ent_root):
for f in fol:
if f[0] == ent_root:
return f[1]
return False
def check_neg(self, word, language):
pos = wordnet.ADV
syns = wordnet.synsets(word, pos=pos, lang=language)
for synset in syns:
if str(synset.name()) in ['no.r.01', 'no.r.02', 'no.r.03', 'not.r.01']:
return True
return False
def get_inc_mask(self, n):
diff = str(bin(int(n, 2) + int("1", 2)))[2:]
delta = len(n) - len(diff)
for i in range(delta):
diff = "0" + diff
return diff
def get_dec_mask(self, n):
diff = str(bin(int(n, 2) - int("00001", 2)))[2:]
delta = len(n) - len(diff)
for i in range(delta):
diff = "0" + diff
return diff
def get_nocount_lemma(self, lemma):
lemma_nocount = ""
total_lemma = lemma.split("_")
for i in range(len(total_lemma)):
if i == 0:
lemma_nocount = total_lemma[i].split(':')[0][:-2] + ":" + total_lemma[i].split(':')[1]
else:
lemma_nocount = total_lemma[i].split(':')[0][:-2] + ":" + total_lemma[i].split(':')[1] + "_" + lemma_nocount
return lemma_nocount
def process_fol(self, vect_fol, id, voc):
print("\n------DICTIONARY------")
print(voc)
print("----------------------\n")
# actions-crossing var list
var_crossing = []
admissible_vars = ['x']
# prepositions
for v in vect_fol:
if len(v) == 3:
label = self.get_nocount_lemma(v[0])
if GEN_PREP is False or id == "LEFT":
if INCLUDE_PRP_POS:
lemma = label
else:
lemma = parser.get_lemma(label)
self.assert_belief(PREP(str(id), v[1], lemma, v[2]))
print("PREP(" + str(id) + ", " + v[1] + ", " + lemma + ", " + v[2] + ")")
if v[1] not in admissible_vars:
admissible_vars.append(v[1])
if v[2] not in admissible_vars:
admissible_vars.append(v[2])
elif v[0] in voc and voc[v[0]] is True:
if INCLUDE_PRP_POS:
lemma = label
else:
lemma = parser.get_lemma(label)
self.assert_belief(PREP(str(id), v[1], lemma, v[2]))
print("PREP(" + str(id) + ", " + v[1] + ", " + lemma + ", " + v[2] + ")")
if v[1] not in admissible_vars:
admissible_vars.append(v[1])
if v[2] not in admissible_vars:
admissible_vars.append(v[2])
# actions
for v in vect_fol:
ACTION_ASSERTED = False
if len(v) == 4:
label = self.get_nocount_lemma(v[0])
pos = self.get_pos(v[0])
if INCLUDE_ACT_POS:
lemma = label
else:
lemma = parser.get_lemma(label)
if GEN_EXTRA is True and pos in GEN_EXTRA_POS:
if (v[0] in voc and voc[v[0]] is True):
self.assert_belief(ACTION(str(id), lemma, v[1], v[2], v[3]))
print("ACTION(" + str(id) + ", " + lemma + ", " + v[1] + ", " + v[2] + ", " + v[3] + ")")
ACTION_ASSERTED = True
else:
self.assert_belief(ACTION(str(id), lemma, v[1], v[2], v[3]))
print("ACTION(" + str(id) + ", " + lemma + ", " + v[1] + ", " + v[2] + ", " + v[3] + ")")
ACTION_ASSERTED = True
if ACTION_ASSERTED:
# check for var action crossing
if v[2] in var_crossing:
self.assert_belief(ACT_CROSS_VAR(str(id), v[2], lemma))
print("ACT_CROSS_VAR(" + str(id) + ")")
else:
var_crossing.append(v[2])
if v[3] in var_crossing:
self.assert_belief(ACT_CROSS_VAR(str(id), v[3], lemma))
print("ACT_CROSS_VAR(" + str(id) + ")")
else:
var_crossing.append(v[3])
if v[1] not in admissible_vars:
admissible_vars.append(v[1])
if v[2] not in admissible_vars:
admissible_vars.append(v[2])
if v[3] not in admissible_vars:
admissible_vars.append(v[3])
# nouns
for v in vect_fol:
if len(v) == 2:
if self.get_pos(v[0]) in ['NNP', 'NNPS', 'PRP', 'CD', 'NN', 'NNS', 'PRP', 'PRP$']:
label = self.get_nocount_lemma(v[0])
if INCLUDE_NOUNS_POS:
lemma = label
else:
lemma = parser.get_lemma(label)
if v[1] in admissible_vars:
self.assert_belief(GND(str(id), v[1], lemma))
print("GND(" + str(id) + ", " + v[1] + ", " + lemma + ")")
# adjectives, adverbs
for v in vect_fol:
if self.get_pos(v[0]) in ['JJ', 'JJR', 'JJS']:
label = self.get_nocount_lemma(v[0])
if GEN_ADJ is False or id == "LEFT":
if INCLUDE_ADJ_POS:
lemma = label
else:
lemma = parser.get_lemma(label)
if v[1] in admissible_vars:
self.assert_belief(ADJ(str(id), v[1], lemma))
print("ADJ(" + str(id) + ", " + v[1] + ", " + lemma + ")")
elif v[0] in voc and voc[v[0]] is True:
if INCLUDE_ADJ_POS:
lemma = label
else:
lemma = parser.get_lemma(label)
if v[1] in admissible_vars:
self.assert_belief(ADJ(str(id), v[1], lemma))
print("ADJ(" + str(id) + ", " + v[1] + ", " + lemma + ")")
elif self.get_pos(v[0]) in ['RB', 'RBR', 'RBS', 'RP']:
label = self.get_nocount_lemma(v[0])
if GEN_ADV is False or id == "LEFT":
if INCLUDE_ADV_POS:
lemma = label
else:
lemma = parser.get_lemma(label)
if v[1] in admissible_vars:
self.assert_belief(ADV(str(id), v[1], lemma))
print("ADV(" + str(id) + ", " + v[1] + ", " + lemma + ")")
elif v[0] in voc and voc[v[0]] is True:
lemma = parser.get_lemma(label)
if v[1] in admissible_vars:
self.assert_belief(ADV(str(id), v[1], lemma))
print("ADV(" + str(id) + ", " + v[1] + ", " + lemma + ")")
def get_pos(self, s):
first = s.split('_')[0]
s_list = first.split(':')
if len(s_list) > 1:
return s_list[1]
else:
return s_list[0]
def get_lemma(self, s):
s_list = s.split(':')
return s_list[0]
class retract_clause(Action):
def execute(self, *args):
sentence = args[0]()
mf = parser.morph(sentence)
print("\n" + mf)
def_clause = expr(mf)
if def_clause in kb_fol.clauses:
kb_fol.retract(def_clause)
# deleting from LKB too?
class new_clause(Action):
def execute(self, *args):
clause = args[0]()
start_time = time.time()
#print("\n", sentence)
mf = parser.morph(clause)
print("\n", mf)
def_clause = expr(mf)
sentence = parser.get_last_sentence()
kb_fol.nested_tell(def_clause, sentence)
if LKB_USAGE:
lkbm.insert_clause_db(mf, sentence)
class reason(Action):
def execute(self, *args):
definite_clause = args[0]()
start_time = time.time()
q = parser.morph(definite_clause)
print("Query: " + q)
print("OCCUR_CHECK: ", exec_occur_check)
bc_result = kb_fol.ask(expr(q))
print("\n ---- Backward-Chaining REASONING ---\n")
print("Result: " + str(bc_result))
end_time1 = time.time()
query_time1 = end_time1 - start_time
print("Backward-Chaining Query time: ", query_time1)
candidates = []
nested_result = False
# first attempt using Backward-chaining (it will return False of substitutions)
if bc_result is not False:
self.assert_belief(OUT("From HKB (Backward-Chaining): True"))
self.assert_belief(OUT(str(bc_result)))
self.assert_belief(ANSWERED("YES"))
else:
print("OUTPUT:", str(bc_result))
self.assert_belief(OUT("From HKB (Backward-Chaining): False"))
# Second attempt using Nested Reasoning (when Backward-chaining result is False)
if bc_result is False and NESTED_REASONING:
print("\n\n ---- NESTED REASONING ---")
nested_result = kb_fol.nested_ask(expr(q), candidates)
if nested_result is False:
print("\nResult: ", nested_result)
self.assert_belief(OUT("From HKB (Nested Reasoning): False"))
else:
print("\nResult: ", nested_result)
self.assert_belief(OUT("From HKB (Nested Reasoning): True"))
self.assert_belief(OUT(str(nested_result)))
self.assert_belief(ANSWERED("YES"))
# Third attempt using Low Knowledge base and previous reasoning are false
if LKB_USAGE and bc_result is False and nested_result is False:
print("\n\n ---- Backward-Chaining REASONING from Lower KB ---")
print("\nquery: ", q)
print("\nMIN_CONFIDENCE: ", MIN_CONFIDENCE)
aggregated_clauses = lkbm.aggregate_clauses(q, [], MIN_CONFIDENCE)
num_aggregated_clauses = len(aggregated_clauses)
print("\nnumber asserted clauses: ", num_aggregated_clauses)
for a in aggregated_clauses:
kb_fol.tell(expr(a))
bc_result = kb_fol.ask(expr(q))
print("\nResult: ", bc_result)
candidates = []
if bc_result is not False:
self.assert_belief(OUT("From LKB (Backward-Chaining): True"))
self.assert_belief(OUT(str(bc_result)))
self.assert_belief(ANSWERED("YES"))
elif bc_result is False and NESTED_REASONING:
print("\n\n ---- NESTED REASONING from Lower KB ---")
nested_result = kb_fol.nested_ask(expr(q), candidates)
if nested_result is False:
print("\nResult: ", nested_result)
self.assert_belief(OUT("From LKB (Nested Reasoning): False"))
else:
print("\nResult: ", nested_result)
self.assert_belief(OUT("From LKB (Nested Reasoning): True"))
self.assert_belief(OUT(str(nested_result)))
self.assert_belief(ANSWERED("YES"))
else:
self.assert_belief(OUT("From LKB (Backward-Chaining): False"))
reason_keys = lkbm.get_last_keys()
print("\nreason keys:", reason_keys)
lkbm.reset_last_keys()
confidence = lkbm.get_confidence()
print("Initial confidence:", confidence)
lkbm.reset_confidence()
print("\nCandidates: ", candidates)
print("\nRelated sentences:\n")
unique_sentences = []
for rk in reason_keys:
sentence = lkbm.get_sentence_from_db(rk)
if len(sentence) > 0:
if sentence not in unique_sentences:
unique_sentences.append(sentence)
for uq in unique_sentences:
print(uq)
if SHOW_REL:
related = uq+" ("+str(confidence)+")"
self.assert_belief(RELATED(related))
# emptying Higher KB
if EMPTY_HKB_AFTER_REASONING:
kb_fol.clauses = []
class assert_command(Action):
def execute(self):
deps = parser.get_last_deps()
MST = parser.get_last_MST()
vect_LR_fol = fol_manager.build_LR_fol(MST, 'd')
# getting fol's type
check_isa = False
check_implication = fol_manager.check_implication(vect_LR_fol)
if check_implication is False:
check_isa = fol_manager.check_isa(vect_LR_fol, deps)
gentle_LR_fol = fol_manager.vect_LR_to_gentle_LR(vect_LR_fol, deps, check_implication, check_isa)
print(str(gentle_LR_fol))
if len(vect_LR_fol) > 1 and vect_LR_fol[1][0] == "==>":
dateTimeObj = datetime.now()
id_routine = dateTimeObj.microsecond
self.process_conditions(vect_LR_fol[0], id_routine)
self.process_routine(vect_LR_fol[2], id_routine)
else:
self.process(vect_LR_fol)
def process_conditions(self, vect_fol, id_routine):
dateTimeObj = datetime.now()
id_ground = dateTimeObj.microsecond
for g in vect_fol:
if len(g) == 3:
lemma = self.get_lemma(g[0])[:-2]
self.assert_belief(COND_PRE_MOD(g[1], lemma, g[2]))
for g in vect_fol:
if len(g) == 2:
lemma = self.get_lemma(g[0])[:-2]