-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReasoner.d
1825 lines (1363 loc) · 55.6 KB
/
Reasoner.d
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
// Copyright 2019 Robert Wünsche
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module Reasoner;
import std.array;
import std.random;
import std.math : pow, abs;
import std.stdio : writeln;
import std.algorithm.mutation;
import std.algorithm.comparison;
import std.algorithm.sorting : sort;
import std.conv : to;
//import core.sync.mutex;
import core.atomic;
import std.typecons : Nullable;
import std.parallelism;
import std.concurrency;
import Stamp : Stamp;
import TruthValue : TruthValue, calcExp, calcProjectedConf;
import Terms : Term, Interval, IntervalImpl, Binary, BinaryTerm, AtomicTerm, isAtomic;
import TermTools;
import Sentence : Sentence, isQuestion, isJudgment, convToStr;
void main() {
//test0(3000);
//testQuestionDerivation0();
//testTemporalSimple0();
//testTemporalInduction1();
testTemporalInduction1();
//testMaze0();
}
// more complex induction example, triggers various rules
void testMaze0() {
shared Reasoner reasoner = new shared Reasoner();
reasoner.init();
{ // add existing belief
shared Term term = new shared Binary("<->", new shared AtomicTerm("m10"), new shared AtomicTerm("m20"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto beliefSentence = new shared Sentence('.', term, tv, stamp);
reasoner.mem.conceptualize(beliefSentence.term);
reasoner.mem.addBeliefToConcepts(beliefSentence);
}
{ // add existing belief
shared Term term = new shared Binary("<->", new shared AtomicTerm("m20"), new shared AtomicTerm("m30"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto beliefSentence = new shared Sentence('.', term, tv, stamp);
reasoner.mem.conceptualize(beliefSentence.term);
reasoner.mem.addBeliefToConcepts(beliefSentence);
}
{ // add existing belief
shared Term term = new shared Binary("<->", new shared AtomicTerm("m30"), new shared AtomicTerm("m40"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto beliefSentence = new shared Sentence('.', term, tv, stamp);
reasoner.mem.conceptualize(beliefSentence.term);
reasoner.mem.addBeliefToConcepts(beliefSentence);
}
{ // add task
shared Term term = new shared Binary("<->", new shared AtomicTerm("m00"), new shared AtomicTerm("m10"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto sentence = new shared Sentence('.', term, tv, stamp);
auto task = new shared Task();
task.sentence = sentence;
reasoner.mem.workingMemory.activeTasks ~= new shared TaskWithAttention(task, 1.0, 1.0, reasoner.cycleCounter);
}
foreach(long i;0..5000) {
reasoner.singleCycle();
}
}
// more complex induction example, triggers various rules
void testTemporalInduction1() {
shared Reasoner reasoner = new shared Reasoner();
reasoner.init();
foreach(int iRepetition; 0..5) {
foreach(string iTermName; ["A","B","C","D","E"]) {
{
shared Term term = new shared Binary("-->", new shared AtomicTerm(iTermName), new shared AtomicTerm("e"));
auto tv = new shared TruthValue(1.0f, 0.9f);
reasoner.event(term, tv);
}
foreach(long i;0..5) {
reasoner.singleCycle();
}
}
}
foreach(long i;0..200000) {
reasoner.singleCycle();
}
}
void testTemporalInduction0() {
shared Reasoner reasoner = new shared Reasoner();
reasoner.init();
// trigger rule A B |- <A =/>+5 B>
{
shared Term term = new shared AtomicTerm("A");
auto tv = new shared TruthValue(1.0f, 0.9f);
reasoner.event(term, tv);
}
foreach(long i;0..5) {
reasoner.singleCycle();
}
{ // add task
shared Term term = new shared AtomicTerm("B");
auto tv = new shared TruthValue(1.0f, 0.9f);
reasoner.event(term, tv);
}
foreach(long i;0..60) {
reasoner.singleCycle();
}
}
// tests simple temporal inference rule
void testTemporalSimple0() {
shared Reasoner reasoner = new shared Reasoner();
reasoner.init();
// trigger rule ('&/', 'A', 't') =/> B), (('&/', 'C', 'z') =/> B) |- (('&/', 'A', 't') =/> C)
{ // add existing belief
shared Term term = new shared Binary("=/>", new shared Binary("&/", new shared AtomicTerm("A"), new shared IntervalImpl(5)), new shared AtomicTerm("B"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto beliefSentence = new shared Sentence('.', term, tv, stamp);
reasoner.mem.conceptualize(beliefSentence.term);
reasoner.mem.addBeliefToConcepts(beliefSentence);
}
{ // add task
shared Term term = new shared Binary("=/>", new shared Binary("&/", new shared AtomicTerm("C"), new shared IntervalImpl(5)), new shared AtomicTerm("B"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto sentence = new shared Sentence('.', term, tv, stamp);
auto task = new shared Task();
task.sentence = sentence;
reasoner.mem.workingMemory.activeTasks ~= new shared TaskWithAttention(task, 1.0, 1.0, reasoner.cycleCounter);
}
foreach(long i;0..60) {
reasoner.singleCycle();
}
}
// tests if a question can be derived
// TODO< automate as unittest and check if it derives the question >
void testQuestionDerivation0() {
shared Reasoner reasoner = new shared Reasoner();
reasoner.init();
{ // add existing belief
shared Term term = new shared Binary("-->", new shared AtomicTerm("a"), new shared AtomicTerm("b"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto beliefSentence = new shared Sentence('.', term, tv, stamp);
reasoner.mem.conceptualize(beliefSentence.term);
reasoner.mem.addBeliefToConcepts(beliefSentence);
}
{ // add question task
shared Term term = new shared Binary("-->", new shared AtomicTerm("b"), new shared AtomicTerm("c"));
auto tv = null;
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto sentence = new shared Sentence('?', term, tv, stamp);
auto task = new shared Task();
task.sentence = sentence;
reasoner.mem.workingMemory.activeTasks ~= new shared TaskWithAttention(task, 1.0, 1.0, reasoner.cycleCounter);
}
foreach(long i;0..100) {
reasoner.singleCycle();
}
}
// tests some complex interactions of the inference
void test0(int numberOfCycles) {
shared Reasoner reasoner = new shared Reasoner();
reasoner.init();
// add existing belief
{
shared Term term = new shared Binary("-->", new shared AtomicTerm("b"), new shared AtomicTerm("c"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto beliefSentence = new shared Sentence('.', term, tv, stamp);
reasoner.mem.conceptualize(beliefSentence.term);
reasoner.mem.addBeliefToConcepts(beliefSentence);
}
{
shared Term term = new shared Binary("-->", new shared AtomicTerm("c"), new shared AtomicTerm("d"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto beliefSentence = new shared Sentence('.', term, tv, stamp);
reasoner.mem.conceptualize(beliefSentence.term);
reasoner.mem.addBeliefToConcepts(beliefSentence);
}
{ // add test question
shared Term term = new shared Binary("-->", new shared AtomicTerm("b"), new shared AtomicTerm("d"));
reasoner.mem.conceptualize(term);
reasoner.mem.addQuestionToConcepts(term);
}
/*
{
shared Term term = new shared Binary("-->", new shared AtomicTerm("d"), new shared AtomicTerm("e"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto beliefSentence = new shared Sentence(term, tv, stamp);
reasoner.mem.conceptualize(beliefSentence.term);
reasoner.mem.addBeliefToConcepts(beliefSentence);
}
{
shared Term term = new shared Binary("-->", new shared AtomicTerm("e"), new shared AtomicTerm("f"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto beliefSentence = new shared Sentence(term, tv, stamp);
reasoner.mem.conceptualize(beliefSentence.term);
reasoner.mem.addBeliefToConcepts(beliefSentence);
}
{
shared Term term = new shared Binary("<=>", new shared AtomicTerm("b"), new shared AtomicTerm("c"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto beliefSentence = new shared Sentence(term, tv, stamp);
reasoner.mem.conceptualize(beliefSentence.term);
reasoner.mem.addBeliefToConcepts(beliefSentence);
}
*/
{
foreach(string iCopula; ["<->", "==>", "<|>", "=/>"]) {
auto termNames = ["a", "b", "c", "d", "e", "f", "g", "h"];
for(int i=0;i<termNames.length-1;i++) {
auto termName0 = termNames[i];
auto termName1 = termNames[i+1];
shared Term term = new shared Binary(iCopula, new shared AtomicTerm(termName0), new shared AtomicTerm(termName1));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto sentence = new shared Sentence('.', term, tv, stamp);
auto task = new shared Task();
task.sentence = sentence;
reasoner.mem.workingMemory.activeTasks ~= new shared TaskWithAttention(task, 1.0, 1.0, reasoner.cycleCounter);
}
for(int i=0;i<termNames.length-1;i++) {
auto termName0 = termNames[i];
auto termName1 = termNames[i+1];
shared Term term = new shared Binary(iCopula, new shared AtomicTerm(termName0), new shared AtomicTerm(termName1));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto beliefSentence = new shared Sentence('.', term, tv, stamp);
reasoner.mem.conceptualize(beliefSentence.term);
reasoner.mem.addBeliefToConcepts(beliefSentence);
}
}
}
{
shared Term term = new shared Binary("-->", new shared AtomicTerm("d"), new shared AtomicTerm("c"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto sentence = new shared Sentence('.', term, tv, stamp);
auto task = new shared Task();
task.sentence = sentence;
reasoner.mem.workingMemory.activeTasks ~= new shared TaskWithAttention(task, 1.0, 1.0, reasoner.cycleCounter);
}
{
shared Term term = new shared Binary("<=>", new shared AtomicTerm("a"), new shared AtomicTerm("b"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto sentence = new shared Sentence('.', term, tv, stamp);
auto task = new shared Task();
task.sentence = sentence;
reasoner.mem.workingMemory.activeTasks ~= new shared TaskWithAttention(task, 1.0, 1.0, reasoner.cycleCounter);
}
/*
{
shared Term term = new shared Binary("<->", new shared AtomicTerm("a"), new shared AtomicTerm("b"));
auto tv = new shared TruthValue(1.0f, 0.9f);
auto stamp = Stamp.makeEternal([reasoner.mem.retUniqueStampCounter()]);
auto sentence = new shared Sentence(term, tv, stamp);
auto task = new shared Task();
task.sentence = sentence;
reasoner.mem.workingMemory.activeTasks ~= new shared TaskWithAttention(task, reasoner.cycleCounter);
}
*/
foreach(long i;0..numberOfCycles) { // TEST REASONING LOOP
reasoner.singleCycle();
}
}
////////////////////////////////
////////////////////////////////
// Attention
/**
* working memory implements some functionality of attention
*
* mechanisms are inspired by ALANN(2018)
*/
class WorkingMemory {
TaskWithAttention[] activeTasks;
public long maxNumberOfTasks = 200000; // Reasoner parameter!
}
void attentionTasksLimit(shared WorkingMemory wm) {
wm.activeTasks = wm.activeTasks[0..min(wm.activeTasks.length, wm.maxNumberOfTasks)];
}
// checks if a task with the specific stamp is already in the list of active tasks
bool attentionHasActiveTaskByStamp(shared WorkingMemory wm, shared Stamp stamp) {
// TODO< use dict by hash of the stamp >
foreach(shared TaskWithAttention iTaskWithAv; wm.activeTasks) {
if (Stamp.equals(stamp, iTaskWithAv.task.sentence.stamp)) {
return true;
}
}
return false;
}
// called when the attention values have to get recomputed for the most important tasks
void attentionUpdateQuick(shared WorkingMemory wm, long cycleCounter) {
bool debugVerbose = false;
// TODO< remove from array and insert again with insertion sort >
foreach(shared TaskWithAttention iTaskWithAttention; wm.activeTasks) {
// we update the exponential-moving-average
// with the accumulated value - to slowly pull it to the accumulated value while considering the history of the EMA
iTaskWithAttention.ema.update(0.0 /* TODO< pull it from the accumulated value which is computed by weighting */);
// we need to reset the accumulated value to allow it to accumulate a new value until the next step
// TODO< implement setting of weighted accumulator to 0.0 >
}
if (debugVerbose) {
foreach(shared TaskWithAttention iTaskWithAttention; wm.activeTasks) {
writeln(
"attention: updated ranking of " ~
"task.sentence=" ~ iTaskWithAttention.task.sentence.convToStr() ~" " ~ iTaskWithAttention.task.sentence.stamp.convToStr() ~ " " ~
"to ranking=" ~ to!string(iTaskWithAttention.calcRanking(cycleCounter))
);
}
}
}
// task with ema of activation
shared class TaskWithAttention {
shared Task task;
Ema ema; // ema used to compute activation
immutable long startSystemCycleTime;
double emaFactor; // factor to eep track of the value up to which the result can grow when EMA returns 1.0
// commented because the logic to accumulate it is not implemented
// double weightedActivationAccumulatorWeight = 0.0;
// double weightedActivationAccumulator = 0.0; // accumulates the activation - used to "pull" the EMA to this value in the next update
// /param startValue additive start priority
// /param emaFactor factor up to which the ema can grow
// /param startSystemCycleTime cycle time of the system when the attention value was created
public shared this(shared Task task, double startValue, double emaFactor, long startSystemCycleTime) {
this.task = task;
this.startSystemCycleTime = startSystemCycleTime;
this.emaFactor = emaFactor;
ema.k = 0.1; // TODO< refine and expose parameter >
ema.ema = startValue;
}
// /param systemCycleTime
public shared double calcRanking(long systemCycleTime) {
float questionVirtualConfidenceValue = 1.0; // is a virtual confidence for questions - can be used to prioritize questions over judgements and goals
double agingBase = 1.2; // how fast does the priority decay based on time
double age = (systemCycleTime - startSystemCycleTime) * 0.1;
double conf = task.sentence.isQuestion() ? questionVirtualConfidenceValue : task.sentence.truth.conf;
double ranking = conf;
ranking += (
pow(agingBase, -age) * ema.ema * // aging with the exponential decay and multiplication with EMA is necessary, because tasks may else be able to boost themself indefinitly to 1.0
emaFactor); // multiply it with ema factor to limit the influence of EMA
return ranking;
}
}
// called when ever a belief of the concept changes
void attentionHandleBeliefUpdate(shared Concept concept, shared Sentence updatedBelief) {
// assert concept.beliefs.entries.length > 0 // there must be at least one updated belief
// compute average exp of all beliefs and update cached value in Concept
double expSum = 0;
foreach(shared Sentence iBelief; concept.beliefs.entries) {
expSum += iBelief.truth.calcExp();
}
concept.cachedAverageExp = expSum / concept.beliefs.entries.length;
}
// called when the system needs to remove superfluous concepts
void attentionRemoveIrrelevantConcepts(shared Memory mem) {
if (mem.concepts.retSize() <= mem.maxNumberOfConcepts) {
return;
}
bool debugForgettingVerbose = false;
long numberOfConceptsToRemove = mem.concepts.retSize() - mem.maxNumberOfConcepts;
class RemoveConceptEntity {
public long conceptIdx;
public shared Concept concept;
public final this(shared Concept concept, long conceptIdx) {
this.concept = concept;
this.conceptIdx = conceptIdx;
}
}
RemoveConceptEntity[] candidates = []; // list of candidates for removal
// updates the candidates if necessary
void updateCandidates(shared Concept concept, long conceptIdx) {
candidates ~= new RemoveConceptEntity(concept, conceptIdx);
// sort by averageExp of beliefs
candidates.sort!("a.concept.cachedAverageExp < b.concept.cachedAverageExp");
// remove entities which survived because they have a high enough exp
//writeln("#remove = ", numberOfConceptsToRemove);
//writeln("len = ", candidates.length);
//writeln("maxIdx = ", min(candidates.length, numberOfConceptsToRemove));
candidates = candidates[0..min(candidates.length, numberOfConceptsToRemove)];
}
for (long idx=0;idx<mem.concepts.retSize();idx++) {
auto iConcept = mem.concepts.retAt(idx);
updateCandidates(iConcept, idx);
}
{ // remove candidates
candidates.sort!("a.conceptIdx > b.conceptIdx");
if (candidates.length >= 2) {
assert(candidates[0].conceptIdx > candidates[1].conceptIdx); // make sure we sorted the right way
}
foreach(RemoveConceptEntity iCandidate; candidates) {
if (debugForgettingVerbose) {
writeln("forgot concept term=", iCandidate.concept.name.convToStrRec(), " beliefs.avgExp=", iCandidate.concept.cachedAverageExp);
}
mem.concepts.removeAt(iCandidate.conceptIdx);
}
}
}
// exponential moving average
// see for explaination https://www.investopedia.com/ask/answers/122314/what-exponential-moving-average-ema-formula-and-how-ema-calculated.asp
struct Ema {
double k = 1; // adaptivity factor
double ema = 0;
public final shared double update(double value) {
ema = value * k + ema * (1.0 - k);
return ema;
}
}
///////////////////////////////
///////////////////////////////
//
shared class Memory {
public WorkingMemory workingMemory;
public ConceptTable concepts;
public Xorshift rng = Xorshift(24);
public int numberOfBeliefs = 40; // Reasoner parameter!
public long maxNumberOfConcepts = 3000; // Reasoner parameter!
private long stampCounter = 0;
public final this() {
concepts = new ConceptTable();
workingMemory = new WorkingMemory();
stampCounter = 0;
}
public final shared long retUniqueStampCounter() {
long result;
synchronized {
result = stampCounter;
core.atomic.atomicOp!"+="(this.stampCounter, 1);
}
return result;
}
public final Sentences infer(shared Task t, shared Concept c, shared TrieDeriver deriver) {
Sentences resultSentences = new Sentences();
// pick random belief and try to do inference
if (c.beliefs.entries.length == 0) {
return resultSentences; // can't select a belief to do inference
}
Xorshift rng2 = cast(XorshiftEngine!(uint, 128u, 11u, 8u, 19u))rng;
long beliefIdx = uniform(0, cast(int)c.beliefs.entries.length, rng2);
rng = cast(shared(XorshiftEngine!(uint, 128u, 11u, 8u, 19u)))rng2;
//writeln("Memory.infer() selectedBeliefIdx=", beliefIdx, " of ", c.beliefs.entries.length); // for debugging problems with rng
auto selectedBelief = c.beliefs.entries[beliefIdx];
if (Stamp.checkOverlap(t.sentence.stamp, selectedBelief.stamp)) {
return resultSentences;
}
deriver.derive(t.sentence, selectedBelief, resultSentences);
return resultSentences;
}
// creates concepts if necessary and puts the belief into all relevant concepts
public final void conceptualize(shared Term term) {
bool debugVerbose = false;
// conceptualizes by selected term recursivly
void conceptualizeByTermRec(shared Term term) {
if(debugVerbose) writeln("conceptualize: called for term=" ~ convToStrRec(term));
if(!concepts.hasConceptByName(term)) {
// create concept and insert into table
if(debugVerbose) writeln("conceptualize: created concept for term=" ~ convToStrRec(term));
auto createdConcept = new shared Concept(term, numberOfBeliefs);
concepts.insertConcept(createdConcept);
}
if(debugVerbose) writeln("conceptualize: call recursivly");
{ // call recursivly
if (cast(shared BinaryTerm)term !is null) {
auto binary = cast(shared Binary)term; // TODO< cast to binaryTerm and use methods to access children >
conceptualizeByTermRec(binary.subject);
conceptualizeByTermRec(binary.predicate);
}
else if (isAtomic(term)) {
// we can't recurse into atomics
}
else {
// TODO< call function which throws an exception in debug mode >
throw new Exception("conceptualize(): unhandled case!");
}
}
}
conceptualizeByTermRec(term);
}
}
// adds the question to the concepts (if it doesn't already exist)
public final void addQuestionToConcepts(shared Memory mem, shared Term questionTerm) {
// selects term recursivly
void addQuestionRec(shared Term name) {
// TODO< enable when debuging > assert concepts.hasConceptByName(term)
auto concept = mem.concepts.retConceptByName(name);
addQuestionIfNecessary(concept, questionTerm);
{ // call recursivly
if (cast(shared BinaryTerm)name !is null) {
shared Binary binary = cast(shared Binary)name; // TODO< cast to binaryTerm and use methods to access children >
addQuestionRec(binary.subject);
addQuestionRec(binary.predicate);
}
else if (isAtomic(name)) {
// we can't recurse into atomics
}
else {
// TODO< call function which throws an exception in debug mode >
throw new Exception("conceptualize(): unhandled case!");
}
}
}
addQuestionRec(questionTerm);
}
// adds the belief to the concepts
public final void addBeliefToConcepts(shared Memory mem, shared Sentence belief) {
// selects term recursivly
void addBeliefRec(shared Term name) {
// TODO< enable when debuging > assert concepts.hasConceptByName(term)
auto concept = mem.concepts.retConceptByName(name);
updateBelief(concept, belief);
{ // call recursivly
if (cast(shared BinaryTerm)name !is null) {
shared Binary binary = cast(shared Binary)name; // TODO< cast to binaryTerm and use methods to access children >
addBeliefRec(binary.subject);
addBeliefRec(binary.predicate);
}
else if (isAtomic(name)) {
// we can't recurse into atomics
}
else {
// TODO< call function which throws an exception in debug mode >
throw new Exception("conceptualize(): unhandled case!");
}
}
}
addBeliefRec(belief.term);
}
interface SentenceListener {
void invoke(shared Sentence sentence) shared;
}
interface ConclusionListener : SentenceListener {}
// working for updating beliefs into concepts
void workerFunc() {
bool isDone = false;
while (!isDone) {
void handler(shared Memory mem, shared Sentence iDerivedSentence, shared(Term)[] subterms) {
foreach(shared Term iTerm; subterms) {
auto concept = mem.concepts.retConceptByName(iTerm);
updateBelief(concept, iDerivedSentence);
}
ownerTid.send(cast(int)0); // send message to indicate completion
}
auto msg = receiveOnly!(shared Memory, shared Sentence, shared(Term)[])();
handler(msg[0], msg[1], msg[2]);
}
}
shared class Reasoner {
public Xorshift rng = Xorshift(12);
shared Memory mem;
TrieDeriver deriver = new TrieDeriver();
EventInducer inducer = new EventInducer();
shared Tid worker;
long cycleCounter = 0;
long numberOfDerivationsCounter = 0;
protected shared(ConclusionListener)[] conclusionListeners;
public this() {
mem = new shared Memory();
worker = cast(shared Tid)spawn(&workerFunc);
}
public void init() {
deriver.init();
}
public void registerListener(shared ConclusionListener listener) {
conclusionListeners ~= listener;
}
// called when ever a event happened
// is usually called from outside
public void event(shared Term term, shared TruthValue tv) {
auto stamp = Stamp.makeEvent(cycleCounter, [mem.retUniqueStampCounter()]);
auto eventSentence = new shared Sentence('.', term, tv, stamp);
mem.conceptualize(eventSentence.term);
Sentences resultSentences = new Sentences();
inducer.induceByEvent(this, deriver, resultSentences, eventSentence); // reason about events with other events (or derived conclusions)
shared(Sentence)[] derivedSentences = resultSentences.arr;
derivedConclusions(derivedSentences, null);
}
// called when ever new conclusions were derived which have to get stored
synchronized protected void derivedConclusions(shared(Sentence)[] derivedSentences, shared TaskWithAttention selectedTaskWithAttention) {
{ // debug
if(false) writeln("derived sentences#=", derivedSentences.length);
core.atomic.atomicOp!"+="(this.numberOfDerivationsCounter, derivedSentences.length);
bool showDerivations = false;
if (showDerivations) {
foreach(shared Sentence iDerivedSentence; derivedSentences) {
writeln(" derived ", iDerivedSentence.convToStr() ~ " stamp=" ~ iDerivedSentence.stamp.convToStr());
}
}
}
{ // put derived results into concepts
foreach(shared Sentence iDerivedSentence; derivedSentences) {
mem.conceptualize(iDerivedSentence.term);
if (iDerivedSentence.isJudgment()) {
auto subterms = enumerateUniqueTermsRec(iDerivedSentence.term);
(cast(Tid)worker).send(mem, iDerivedSentence, subterms[0..subterms.length/2]);
foreach(shared Term iTerm; subterms[subterms.length/2..$]) {
auto concept = mem.concepts.retConceptByName(iTerm);
updateBelief(concept, iDerivedSentence);
}
int result = receiveOnly!int();
}
// TODO< put derived question into concepts >
}
}
{ // ATTENTION< we need to spawn tasks for the derived results - but we need to manage attention with a activation value
foreach(shared Sentence iDerivedSentence; derivedSentences) {
auto task = new shared Task();
task.sentence = iDerivedSentence;
bool isActiveByStamp = attentionHasActiveTaskByStamp(mem.workingMemory, task.sentence.stamp);
if (isActiveByStamp) {
continue; // we don't add it to the tasks if it was already derived
// we check by stamp because it is a good way to make sure so
}
// compute base attention value by type of conclusion
// (1.0 if it is not a question, questions AV * factor)
double emaFactor = 1.0;
if (iDerivedSentence.isQuestion()) {
double derivedQuestionFactor = 0.9; // how much is the attention of a question punhished when it was drived from a parent question
emaFactor = selectedTaskWithAttention.emaFactor * derivedQuestionFactor;
}
double baseAttentionValue = 0.0;
if (selectedTaskWithAttention !is null) {
baseAttentionValue = selectedTaskWithAttention.ema.ema;
}
auto createdTask = new shared TaskWithAttention(task, baseAttentionValue, emaFactor, cycleCounter);
auto arr = cast(TaskWithAttention[])mem.workingMemory.activeTasks; // HACK< needs some casting because the standard library doesn't define insertInPlace for shared objects ! >
arr.insertInPlace(0, cast(TaskWithAttention)createdTask);
mem.workingMemory.activeTasks = cast(shared(TaskWithAttention)[])arr;
}
}
{ // send to listeners
foreach(shared Sentence iDerivedSentence; derivedSentences) {
foreach(shared ConclusionListener iListener; conclusionListeners) {
iListener.invoke(iDerivedSentence);
}
}
}
}
public void singleCycle() {
bool debugVerbose = false;
if (debugVerbose) writeln("singleCycle() ENTRY");
scope(exit) if (debugVerbose) writeln("singleCycle() EXIT");
{ // attention - we need to update the AV of highly prioritized items
if ((cycleCounter % 50) == 0) {
attentionUpdateQuick(mem.workingMemory, cycleCounter);
}
}
{ // attention - we need to sort high priority items
if ((cycleCounter % 100) == 0) {
// TODO< sort upper section of tasks
}
}
{ // attention - we need to sort all items
if ((cycleCounter % 5000) == 0) {
auto calcRanking2 = (shared TaskWithAttention a, shared TaskWithAttention b) => a.calcRanking(cycleCounter) > b.calcRanking(cycleCounter);
mem.workingMemory.activeTasks.sort!(calcRanking2);
}
}
{ // attention - we need to limit the number of tasks
if ((cycleCounter % 5000) == 0) {
mem.workingMemory.attentionTasksLimit();
}
}
{ // attention - we may need to remove concepts
if ((cycleCounter % 600) == 0) {
attentionRemoveIrrelevantConcepts(mem);
}
}
shared(Sentence)[] derivedSentences;
shared TaskWithAttention selectedTaskWithAttention;
if(mem.workingMemory.activeTasks.length > 0) {
// select task and process it with selected concepts
{
long mode;
{
Xorshift rng2 = cast(XorshiftEngine!(uint, 128u, 11u, 8u, 19u))rng;
mode = uniform(0, 0xFF, rng2);
rng = cast(shared(XorshiftEngine!(uint, 128u, 11u, 8u, 19u)))rng2;
}
// attention: select the highest prioritized or most recent tasks with a high priority
long selectedLength = mem.workingMemory.activeTasks.length;
if (mode < 0xE0) {
selectedLength = min(256, selectedLength);
}
{ // select random task for processing
Xorshift rng2 = cast(XorshiftEngine!(uint, 128u, 11u, 8u, 19u))rng;
long chosenTaskIndex = uniform(0, selectedLength, rng2);
rng = cast(shared(XorshiftEngine!(uint, 128u, 11u, 8u, 19u)))rng2;
selectedTaskWithAttention = mem.workingMemory.activeTasks[chosenTaskIndex];
}
}
// do test inference and look at the result (s)
{ // pick random n concepts of the enumerated subterms of testtask and do inference for them
shared Task selectedTask = selectedTaskWithAttention.task;
auto termAndSubtermsOfSentenceOfTask = enumerateTermsRec(selectedTask.sentence.term);
int numberOfSampledTerms = 7;
// sample terms from termAndSubtermsOfSentenceOfTask
Xorshift rng2 = cast(XorshiftEngine!(uint, 128u, 11u, 8u, 19u))rng;
auto sampledTerms = sampleFromArray(termAndSubtermsOfSentenceOfTask, numberOfSampledTerms, rng2);
rng = cast(shared(XorshiftEngine!(uint, 128u, 11u, 8u, 19u)))rng2;
/*
// helper function which does the inference concurrently
static shared(Sentence)[] parallelInfer(shared Memory mem, shared Task selectedTask, shared TrieDeriver deriver, shared Term iSampledTerm) {
if (!mem.concepts.hasConceptByName(iSampledTerm)) {
return [];
}
auto selectedConcept = mem.concepts.retConceptByName(iSampledTerm);
//if(debugVerbose) writeln("reasoning: infer for task.sentence=" ~ selectedTask.sentence.convToStr() ~ " concept.name=" ~ convToStrRec(selectedConcept.name));
return mem.infer(selectedTask, selectedConcept, deriver).arr;
}
std.parallelism.Task!(parallelInfer, shared(Memory), shared(Task), shared(TrieDeriver), shared(Term))*[] parallelInfers;
foreach(shared Term iSampledTerm; sampledTerms) {
auto task = std.parallelism.task!parallelInfer(mem, selectedTask, deriver, iSampledTerm);
taskPool.put(task); //task.executeInNewThread();
parallelInfers ~= task;
}
foreach(std.parallelism.Task!(parallelInfer, shared(Memory), shared(Task), shared(TrieDeriver), shared(Term))* iInfer; parallelInfers) {
derivedSentences ~= iInfer.yieldForce;
}
// */
//* commented because it is the not parallel version
{ // do inference for the concepts named by sampledTerms
foreach(shared Term iSampledTerm; sampledTerms) {
if (!mem.concepts.hasConceptByName(iSampledTerm)) {
continue;
}