-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnar.nim
4738 lines (2848 loc) · 127 KB
/
nar.nim
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 std/strformat
import std/algorithm
import std/tables
import std/sequtils
import random
import std/options
import std/math
import tv
import stamp
import term
import narsese
import unify
# import tsetlin0 # commented because not used yet for control
# compile and run with
# nim compile --run nar.nim
var enPerception1: bool = true # enable perception1 perception engine? - disable only for debugging
var enPerceptionLayer: bool = false # enable "perception layer" specialized perception deriver for complicated predImpl's
# DEPRECATED
var enProceduralSampleAndBuildContigency: bool = false # enable sample and build contigency perception engine?
const STAMPMAXLEN: int = 25
var verbosityDbgA: int = 0 # verbosity for some debugging of deriver
var procRng: Rand = initRand(345) # rng for procedural reasoner
proc debug0(msg:string, verbosity: int = 1) =
if verbosity <= 2:
debugEcho fmt"DBG: {msg}"
# call when something non-critical recoverable happened which may indicate a bug
proc fixme0(msg: string) =
debugEcho &"FIXME: {msg}"
var panicDbgModel*: bool = false # set to true that panicDbg() terminates the program
# for debugging only!
proc panicDbg(msg: string) =
debugEcho &"PANICDBG: {msg}"
if panicDbgModel:
quit(2) # quit because of panic
type PunctEnum* = enum
judgement, question, goal
# link of a predictive implication from the predicate to the subject (target)
type PredImplLinkObj* = ref object
target*: TermObj
tv*: Tv # truth value of the predictive implication
stamp*: seq[int64] # stamp of the predictive implication link
pred*: TermObj # predicate of virtual =/>
type SentenceObj* = ref object
term*: TermObj
tv*: Tv
punct*: PunctEnum
stamp*: seq[int64]
# link which points from the predicate to the subject over a predictive implication
# can be nil if it has no link
predImplLinks: seq[PredImplLinkObj]
originContingency: PredImplLinkObj # predimpllink which stands for contingency, which is the origin of that goal, can be nil
# example: (a, ^x)!:|: has originContingency (a, ^x)=/>b.
type
EventObj* = object
s*: SentenceObj
occTime: int64
tvProjected: Tv
proc sentenceEq(a: SentenceObj, b: SentenceObj): bool =
let epsilon: float = 0.0000001
if abs(a.tv.f-b.tv.f) > epsilon or abs(a.tv.evi-b.tv.evi) > epsilon:
return false # can't be equal if the TV is different
if a.punct != b.punct:
return false
if not termEq(a.term, b.term):
return false
return true
# checks if the link exists already, update it if so
# add it if it doesn't exist
proc sentenceUpdateLink(s:SentenceObj, link:PredImplLinkObj) =
# update existing links if necessary
for iLink in s.predImplLinks:
if termEq(iLink.target, link.target):
# update
# TODO LOW
discard
# check if link already exists
for iLink in s.predImplLinks:
if termEq(iLink.target, link.target):
return # yes link already exists, exit because we don't need to add
debug0(&"sentenceUpdateLink(): add link {convTermToStr(link.target)} =/> {convTermToStr(s.term)}")
# add link because it doesn't exist
s.predImplLinks.add(link)
# keep links under AIR
# TODO MID< implement me! >
type
AikrArr*[T] = object
content*: seq[T]
maxLen*: int
# doesn't check if it is valid to insert item
proc insert*[T](arr: var AikrArr[T], v: T) =
arr.content.add(v)
if arr.content.len > arr.maxLen:
# sort
# TODO TODO TODO
arr.content = arr.content[0..arr.maxLen-1]
# CONCEPT
# prediction links point at subj of =/>
# TODO< implement this procedural stuff >
type
ConceptObj* = ref Concept
Concept* = object
name: TermObj
content: AikrArr[SentenceObj]
contentProcedural: AikrArr[SentenceObj] # procedural beliefs, predImpl
# store or revise
proc put(c: ConceptObj, s: SentenceObj) =
for iIdx in 0..<c.content.content.len:
let iContent = c.content.content[iIdx]
if termEq(iContent.term, s.term):
if checkStampOverlap(iContent.stamp, s.stamp):
# choice rule - if statement is the same then select candidate with higher conf
if s.tv.retConf() > iContent.tv.retConf():
c.content.content[iIdx] = s
else:
# revision
# FIXME< replace item at index!!! >
iContent.stamp = merge(iContent.stamp, s.stamp, STAMPMAXLEN)
iContent.tv = tvRev(iContent.tv, s.tv)
return
insert(c.content, s)
# store or revise
proc putPredImpl(c: ConceptObj, s: SentenceObj) =
case s.term.type0
of predImpl:
# returns false when the term of =/> wasnt found
# /param update
proc checkOrUpdate(update: bool): bool =
for iContent in c.content.content:
if termEq(iContent.term, s.term.predicate):
for iPredImplLink in iContent.predImplLinks:
if termEq(iPredImplLink.target, s.term.subject):
# we are here if the term of =/> is the same
# TODO LOW< here we would have to revise/choice rule >
return true
# if we are here then a belief with the same term as s.term wasn't found
if update:
#echo "HERE"
#echo convTermToStr(s.term.subject)
#quit(1)
# add new link and return
var createdLink: PredImplLinkObj = PredImplLinkObj(target:s.term.subject, tv:s.tv, stamp:s.stamp, pred:s.term.predicate)
sentenceUpdateLink(iContent, createdLink)
return true
# if we are here then the term of =/> wasn't found and there is no belief with the right (( B of A=/>B ))
return false
if not checkOrUpdate(false):
var predSentence: SentenceObj = SentenceObj(term:s.term.predicate)
insert(c.content, predSentence)
discard checkOrUpdate(true)
else:
discard
# not expected term, just return silently
# memory
type
MemObj* = ref Mem
Mem* = object
#concepts*: seq[ConceptObj] # OLD
conceptsByName*: Table[TermObj, ConceptObj]
capacityConcepts*: int # PARAM
# initTable[TermObj, ConceptObj]()
# helper to compare priority of concepts
proc compareMemGc(a, b: tuple[c:ConceptObj, worth:float64]): int =
return cmp(a.worth, b.worth)
proc memGc*(mem: MemObj) =
if mem.conceptsByName.len > mem.capacityConcepts:
#var z: seq[ConceptObj] = @[]
var z: seq[tuple[c:ConceptObj, worth:float64]] = @[]
for iKey in mem.conceptsByName.keys:
var tuple0: tuple[c:ConceptObj, worth:float64]
tuple0.c = mem.conceptsByName[iKey]
var worth: float64 = 0.0
for iBelief in tuple0.c.content.content:
worth = max(calcExp(iBelief.tv), worth)
for iBelief in tuple0.c.contentProcedural.content:
worth = max(calcExp(iBelief.tv), worth)
z.add(tuple0)
# * sort
sort(z, compareMemGc)
# * limit
z = z[0..mem.capacityConcepts]
mem.conceptsByName.clear()
for iv in z:
mem.conceptsByName[iv.c.name] = iv.c
# lookup concept by name
proc memLookupConceptByName(mem: MemObj, name: TermObj): ConceptObj =
#echo(&"DBGE {convTermToStr(name)} {hash(name)}")
#echo("ENUM")
# HACKY SLOW WAY to find it!
for iv in mem.conceptsByName.keys:
if hash(iv)==hash(name):
let ic = mem.conceptsByName[iv]
#echo(ic != nil)
return ic
#echo(&"DGGG {convTermToStr(iv)} {hash(iv)}")
return nil
#return mem.conceptsByName[name]
#echo(mem.conceptsByName.hasKey(name))
# hacky slow way because "if name in mem.conceptsByName:" doesn't work with current Nim version!
#try:
# return mem.conceptsByName[name]
#except KeyError as e:
# echo("DBGGG ret nil")
# return nil
# old way which doesn't work because something is buggy in Nim
#if name in mem.conceptsByName:
# return mem.conceptsByName[name]
#return nil
proc retNumberOfConcept*(mem: MemObj): int =
##return mem.concepts.len
return mem.conceptsByName.len
proc reset*(mem: MemObj) =
#mem.concepts = @[]
mem.conceptsByName.clear()
# returns the names of the concepts
proc termRetConcepts(t: TermObj, fullRecursive: bool = false): seq[TermObj] =
var res: seq[TermObj] = @[]
case t.type0
of name:
return @[t]
of inh, predImpl, TermTypeEnum.impl, sim:
res = @[t.subject, t.predicate]
if fullRecursive:
res=res&termRetConcepts(t.subject, fullRecursive)
res=res&termRetConcepts(t.predicate, fullRecursive)
return res
of sequence:
res.add(t) # the term itself, ex: (a, b)
for iv in t.items0:
res.add(iv)
if fullRecursive:
for iv in t.items0:
res=res&termRetConcepts(iv, fullRecursive)
return res
of img:
return t.content
of `tuple`, TermTypeEnum.prod, TermTypeEnum.uvar, TermTypeEnum.qvar:
return @[]
proc convSentenceToStr*(s: SentenceObj): string =
if s == nil:
fixme0(&"convSentenceToStr(): s is nil!")
return "NULL"
var punct="."
if s.punct == goal:
punct="!"
elif s.punct == question:
punct="?"
return fmt"{convTermToStr(s.term)}{punct} {{{s.tv.f} {retConf(s.tv)}}}"
# conv sentence to full string
proc convSentenceToStr2(s: SentenceObj): string =
var res: string = convSentenceToStr(s)
var originContigencyTargetStr: string = "NULL"
if s.originContingency!=nil:
originContigencyTargetStr = convTermToStr(s.originContingency.target)
return res&"\n"&"originContigency.target="&originContigencyTargetStr
var CONCEPTBELIEFMAXN = 15 # capacity of beliefs per concept
# create a concept
# (only call if the concept doesnt exist!)
proc createConcept(mem: MemObj, name: TermObj): ConceptObj =
let concept1: ConceptObj = ConceptObj(name:name, content:AikrArr[SentenceObj](maxLen:CONCEPTBELIEFMAXN))
mem.conceptsByName[name] = concept1
return concept1
# add or revise in memory
proc put(mem: MemObj, s: SentenceObj) =
block: # handling of =/> copula
case s.term.type0
of predImpl:
# * add procedural link of =/>
var c: ConceptObj = memLookupConceptByName(mem, s.term.predicate)
if c == nil:
# we need to create the concept
c = createConcept(mem, s.term.predicate)
c.putPredImpl(s)
return
else:
discard
let touchedConcepts: seq[TermObj] = termRetConcepts(s.term)
# store into concepts
for iConceptName in touchedConcepts:
var c: ConceptObj = memLookupConceptByName(mem, iConceptName)
if c == nil:
# we need to create the concept
c = createConcept(mem, iConceptName)
#DBG debug0(&"put() s={convSentenceToStr(s)} into concept={convTermToStr(c.name)}")
c.put(s)
type
ParseOpResEnum = enum
ParseOpRes
NoneParseRes
ParseOpRes1 = object
case resType: ParseOpResEnum
of ParseOpRes:
name: string
args: seq[TermObj]
of NoneParseRes: null: int
proc tryParseOp(t: TermObj): ParseOpRes1 =
case t.type0
of inh:
let inhSubj = t.subject
let inhPred = t.predicate
case inhPred.type0
of name:
let nameStr = inhPred.name
case inhSubj.type0
of TermTypeEnum.prod:
let args = inhSubj.items0
return ParseOpRes1(resType:ParseOpRes, name:nameStr, args:args)
else:
return ParseOpRes1(resType:NoneParseRes, null:0) # fail
else:
return ParseOpRes1(resType:NoneParseRes, null:0) # fail
else:
return ParseOpRes1(resType:NoneParseRes, null:0) # fail
proc checkIsOp(term: TermObj): bool =
let parseOpResult = tryParseOp(term)
case parseOpResult.resType
of ParseOpRes:
return true
of NoneParseRes:
return false
# NOTE< caller should assume that the input term is a OP in the first place! >
func retOpName(t: TermObj): string =
let z = tryParseOp(t)
case z.resType
of ParseOpRes:
return z.name
else:
return "" # we return "" because we can't return anything meaningful - should not happen
type OpFnType* = proc(args:seq[TermObj]){.closure.}
# type for a registered op
type RegisteredOpRef* = ref object
callback*: OpFnType
#supportsLongCall*: bool # does the op support long calls over many cycles?
supportFlags*: Table[string, bool] # flags assigned to the op
# valid key are "babble" to disable motor babbling
# valid key is "longCall" if the op supports calls over many cycles
# check if a op supports a given flag
func checkOpSupports*(op: RegisteredOpRef, flagName: string, default: bool): bool =
if op.supportFlags.hasKey(flagName):
return default # not found so it supports is based on the default value
return op.supportFlags[flagName]
# helper to create op
func makeOp*(callBack: OpFnType): RegisteredOpRef =
var res = new (RegisteredOpRef)
res.callback = callback
res.supportFlags = initTable[string, bool]()
return res
type
OpRegistryObj* = ref OpRegistry
OpRegistry* = object
ops*: Table[string, RegisteredOpRef] # list with registered ops
type
Task0 = ref Task0Obj
Task0Obj = object
sentence: SentenceObj
prioCached: float # priority of the task (cached value)
bestAnswer: SentenceObj # can be null if nothing found or if it is not a question
type
Taskset0[T] = ref Taskset0Obj[T]
Taskset0Obj[T] = object
set0: seq[T]
cmpFn: proc (a: T, b: T): int
maxLen: int
# insert a task into the set of tasks
proc taskset0Insert[T](taskset: Taskset0[T], task: T) =
taskset.set0.add(task)
#proc cmpFn(a: Task0, b: Task0): int =
# return cmp(a.prioCached, b.prioCached)
taskset.set0.sort(taskset.cmpFn)
# keep under AIKR
taskset.set0 = taskset.set0[0..min(taskSet.maxLen, taskset.set0.len-1)]
# return nil if nothing could be popped of the stack
proc taskset0TryPopTop[T](taskset: Taskset0[T]): T =
if taskset.set0.len == 0:
return nil
let topItem = taskset.set0[0]
taskset.set0.del(0)
return topItem
type
GoalObj* = object
e*: EventObj
type
GoalsWithSameDepthObj* = object
goals*: seq[GoalObj]
depthCached*: int
type
EventRef* = ref EventObj
func convEventToStr(e: EventRef): string =
return &"{convSentenceToStr(e.s)} occTime={e.occTime}"
# HELPER for the UNREFACTORED code which uses new EventRef
func convEventObjToRef(e: EventObj): EventRef =
var res: EventRef = new (EventRef)
res.s = e.s
res.occTime = e.occTime
return res
type
Perception1TaskRef = ref Perception1Task
Perception1Task = object
prioCached: float64
v: EventRef
# helper to sample
# /param rngVal random value between 0.0 and 1.0
func sampleHelper[T](items: seq[tuple[prio:float64,val:T]], rngVal: float): T =
if items.len == 0:
return T.default
var prioSum: float64 = 0.0
for iItem in items:
prioSum += iItem.prio
let selPrio: float64 = prioSum*rngVal
var prioAcc: float64 = 0.0
for iItem in items:
prioAcc += iItem.prio
if prioAcc >= selPrio:
return iItem.val
return items[items.len-1].val # fallback
# ASK< is fallback ever reached? >
# datastructure which is bag like with bag like sampling
# usage: is usually used
type
SampledSetDsRef* = ref SampledSetDs
SampledSetDs* = object
set0*: seq[EventRef]
maxLen*: int
cmpFn*: proc (a: EventRef, b: EventRef): int
proc sampledSetDsMake(maxLen: int): SampledSetDsRef =
var res: SampledSetDsRef = new (SampledSetDsRef)
res.set0 = @[]
res.maxLen = maxLen
proc cmpFn(a: EventRef, b: EventRef): int =
let aVal: float64 = calcExp(a.s.tv)
let bVal: float64 = calcExp(b.s.tv)
return cmp(aVal, bVal)
res.cmpFn = cmpFn
return res
# limit max number of entities to keep under AIKR
proc sampledSetDsLimit*(ds: SampledSetDsRef) =
ds.set0.sort(ds.cmpFn)
ds.set0 = ds.set0[0..min(ds.maxLen, ds.set0.len-1)]
proc sampledSetDsPut(ds: SampledSetDsRef, item: EventRef) =
# check if it already exists (with same stamp and same term and same tv)
for iEvent in ds.set0:
if sentenceEq(iEvent.s, item.s) and iEvent.occTime == item.occTime:
return # no need to do because event is the same
ds.set0.add(item)
sampledSetDsLimit(ds) # keep under AIKR
# sample by distribution
proc sampledSetDsSample(ds: SampledSetDsRef): EventRef =
if ds.set0.len == 0:
return nil # can't sample anything!
# translate items
var items: seq[tuple[prio:float64, val:EventRef]] = @[]
for iItem in ds.set0:
var item: tuple[prio:float64, val:EventRef]
item.prio = calcExp(iItem.s.tv)
item.val = iItem
return sampleHelper(items, procRng.rand(0.0..1.0)) # do actual sampling
discard """
# global set of recently derived events
var narDerivedEventsSampledSetLevel1*: SampledSetDsRef
block:
let maxLen: int = 20
narDerivedEventsSampledSetLevel1 = sampledSetDsMake(maxLen)
# override compare function of the sampled set because we need to consider the recency of the event too
proc cmpFn(a: EventRef, b: EventRef): int =
let decayFactor: float64 = 0.001
let aVal: float64 = calcExp(a.s.tv) * exp(-float64(globalNarInstance.currentTime - a.occTime) * decayFactor)
let bVal: float64 = calcExp(b.s.tv) * exp(-float64(globalNarInstance.currentTime - b.occTime) * decayFactor)
return cmp(aVal, bVal)
narDerivedEventsSampledSetLevel1.cmpFn = cmpFn
"""
# pointer to handler for Q&A
type ConclHandlerPtr = (proc(concl: SentenceObj):void)
type InvokeOpHandlerPtr = (proc(opTerm: TermObj):void)
func nullConclhandler(concl: SentenceObj) =
discard
func nullOpHandler(opTerm: TermObj) =
discard
type
NarCtxRef* = ref NarCtx
NarCtx* = object
conclCallback*: ConclHandlerPtr # callback for done derivation
invokeOpCallback*: InvokeOpHandlerPtr
opRegistry*: OpRegistryObj
mem*: MemObj
goalMem*: MemObj
# idea: * store indirection to belief in hashtable which is indexable by occurence time, this is a real alternative to the windowing approach
# perceivable events by occurence time
# value of the table is a sequence because the same time can have multiple events!
eventsByOccTime*: Table[int64, seq[EventObj]]
# PERCEPTION: set of recently derived events
narDerivedEventsSampledSetLevel1*: SampledSetDsRef
lastPerceivedEvent: EventObj # event which was last perceived
perceptionLayer0lastPerceivedEvent: EventObj
tasksetPerception1*: Taskset0[Perception1TaskRef] # set of tasks for perception1
# goal system
allGoalsByDepth*: seq[GoalsWithSameDepthObj]
currentTime*: int64 # current absolute time
decisionThreshold*: float64 # CONFIG
# global nar instance
# REFACTORME< refactor this into a non-global one once everything got refactored enough >
var globalNarInstance*: NarCtx
#[ commented because I don't know what episodic memory is supposed to be and how to implement it
# we selected the matching episodic memory, now we want to realize the operation of it
#
proc episodicMemRealizeOp(t: TermObj, opRegistry: OpRegistryObj) =
let parseOpResOpt = tryParseOp(t)
if parseOpResOpt.resType == ParseOpRes:
debug0("executive: HERE")
opRegistry.ops[parseOpResOpt.name](parseOpResOpt.args)
# index and execute
proc episodicMemIdxAndInvokeOp(t: TermObj, selIdx: int, opRegistry: OpRegistryObj) =
case t.type0
of inh:
let inhSubj = t.subject
case inhSubj.type0
of `tuple`:
let part0 = inhSubj
let selItem = part0.items0[selIdx] # select by index
episodicMemRealizeOp(selItem, opRegistry) # execute op
of inh, prod, name, predImpl, sequence:
let a=0
of prod, name, `tuple`, predImpl, sequence:
let a=0
]#
proc ruleNal4ProdToImg(aTerm: TermObj, aTv: Tv): seq[tuple[term: TermObj, tv: Tv]] =
case aTerm.type0
of inh:
case aTerm.subject.type0
of TermTypeEnum.prod:
let prod = aTerm.subject
if prod.items0.len == 2: # only implemented for 2 items
let a = prod.items0[0]
let b = prod.items0[1]
var res: seq[tuple[term: TermObj, tv: Tv]] = @[]
block:
var r: tuple[term:TermObj, tv:Tv]
r.term = termMkInh(termMkImg(0, aTerm.predicate, @[b]), a)
r.tv = aTv
res.add(r)
block:
var r: tuple[term:TermObj, tv:Tv]
r.term = termMkInh(termMkImg(1, aTerm.predicate, @[a]), b)
r.tv = aTv
res.add(r)
return res
else:
return @[]
else:
return @[]
else:
return @[]
proc ruleNal4ImgToProd(aTerm: TermObj, aTv: Tv): ref tuple[term:TermObj, tv:Tv] =
case aTerm.type0
of inh:
let subj = aTerm.subject
let pred = aTerm.predicate
case subj.type0
of img:
let img = subj
if img.content.len != 1:
return nil
var a: TermObj
var b: TermObj
if img.idx == 0:
a = pred
b = img.content[0]
else:
a = img.content[0]
b = pred
var res = new (tuple[term:TermObj, tv:Tv])
res.term = termMkInh(termMkProd2(@[a, b]), img.base)
res.tv = aTv
return res
else:
return nil
else:
return nil
# A., A ==> B. |- B.
proc ruleNal6Ded(aTerm: TermObj, aTv: Tv, bTerm: TermObj, bTv: Tv): ref tuple[term:TermObj, tv:Tv] =
case bTerm.type0
of TermTypeEnum.impl:
let subj = bTerm.subject
let pred = bTerm.predicate
# TODO< implement unification here! >
if termEq(aTerm, subj):
let c: ref tuple[term: TermObj, tv: Tv] = new (tuple[term: TermObj, tv: Tv])
c.term = pred
c.tv = tvDed(aTv, bTv) # FIXME< check if this is correct! >
return c
else:
return nil
else:
return nil
# inference rule - derive <==> from two contingencies (RFT)
# (a,<(SELF * ...X...) --> x>) =/> c
# (a,<(SELF * ...Y...) --> x>) =/> c
# |-
# X <==> Y
proc ruleRftExtractRftEquiv(aTerm: TermObj, bTerm: TermObj): TermObj =
proc tryExtract(t: TermObj): ref tuple[predPred:TermObj, seqCondition:TermObj, opName:string, opArgs:seq[TermObj]] =
case t.type0
of predImpl:
let predSubj = t.subject
let predPred = t.predicate
# predSubj must be a seq
case predSubj.type0
of sequence:
# TODO LOW< FIXME<we restrict us here to the case when the sequence has a length of 2> >
if predSubj.items0.len == 2:
let seqCondition = predSubj.items0[0]
let seqItem1 = predSubj.items0[0]
let parseOpResOpt = tryParseOp(seqItem1)
if parseOpResOpt.resType == ParseOpRes:
var res = new (tuple[predPred:TermObj, seqCondition:TermObj, opName:string, opArgs:seq[TermObj]])
res.predPred=predPred
res.seqCondition=seqCondition
res.opName = parseOpResOpt.name
res.opArgs = parseOpResOpt.args
return res
else:
return nil
else:
return nil
else:
return nil
else:
return nil
let x = tryExtract(aTerm)
let y = tryExtract(bTerm)
if x != nil and y != nil:
debug0("ruleRftExtractRftEquiv(): both premises are contingencies!")
# TODO< check if parts of x and y are the same and return the conclusion only if this is the case >
return nil
#return TermObj(type0:RftEquiv, subject:x, predicate:y)
else:
return nil
# mutual entailment as defined by RFT
# https://github.com/opennars/OpenNARS-for-Applications/blob/cef2b292aa29d5d7eed8ea739305191284fae62d/src/NAL.h#L249
# R2VarIntro( (A,Op1) =/> M, (B,Op2) =/> M |- ((A,Op1) =/> M) ==> ((B,Op2) =/> M) tv-fn:Induction
# TODO MID< implement var intro rule exactly like done in ONA >
proc ruleMutualEntailmentA(aTerm: TermObj, aTv: Tv, bTerm: TermObj, bTv: Tv): ref tuple[term: TermObj, tv: Tv] =
case aTerm.type0
of predImpl:
case bTerm.type0:
of predImpl:
#
if termEq(aTerm.predicate, bTerm.predicate):
let aSubj: TermObj = aTerm.subject
let bSubj: TermObj = bTerm.subject
case aSubj.type0
of sequence:
case bSubj.type0
of sequence:
#
let lastSeqItemA: TermObj = aSubj.items0[aSubj.items0.len-1]
let lastSeqItemB: TermObj = bSubj.items0[bSubj.items0.len-1]
# last must be op!
let parseOpAResult = tryParseOp(lastSeqItemA)
case parseOpAResult.resType
of ParseOpRes:
# last must be op!
let parseOpBResult = tryParseOp(lastSeqItemB)
case parseOpAResult.resType
of ParseOpRes:
#
let c: ref tuple[term: TermObj, tv: Tv] = new (tuple[term: TermObj, tv: Tv])
c.term = termMkImpl(aTerm, bTerm)
c.tv = tvInd(aTv, bTv)
return c
of NoneParseRes:
return nil
of NoneParseRes:
return nil
else:
return nil
else:
return nil
else:
return nil
else:
return nil