-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExpDescn3.hx
1246 lines (942 loc) · 37.8 KB
/
ExpDescn3.hx
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 2020 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.
*/
import Executive;
class ExpDescn3 {
// helper for testing etc
// builds a op-call without an argument
public static function buildCallOp(name:String):Term {
return Term.Cop("-->", Term.Prod([Term.Set("{", [Term.Name("SELF")])]), Term.Name(name));
}
// tests if the executive can confirm a anticipation correctly
public static function testAnticipationConfirm1() {
var uut:Executive = new Executive();
uut.randomActProb = 0.0; // we must disable random actions
{ // add anticipation which is assumed to be inflight
var pair = new Pair(uut.createStamp());
pair.effect = new Par([Term.Name("a")]);
uut.anticipationsInflight.push(new InflightAnticipation(pair, 5));
}
uut.step([Term.Name("a"), Term.Name("b")]);
Assert.enforce(uut.anticipationsInflight.length == 0, "anticipation must have been confirmed!");
}
// tests if the executive can confirm a anticipation correctly
public static function testAnticipationConfirm2() {
var uut:Executive = new Executive();
uut.randomActProb = 0.0; // we must disable random actions
{ // add anticipation which is assumed to be inflight
var pair = new Pair(uut.createStamp());
pair.effect = new Par([Term.Name("a"), Term.Name("b")]);
uut.anticipationsInflight.push(new InflightAnticipation(pair, 5));
}
uut.step([Term.Name("a")]);
Assert.enforce(uut.anticipationsInflight.length == 1, "anticipation must not have been confirmed!");
}
// tests if it builds the impl seq even when a empty trace item is present
public static function testTraceEmpty1() {
var uut:Executive = new Executive();
uut.step([Term.Name("a")]);
uut.step([buildCallOp("^b")]);
uut.step([]);
uut.step([Term.Name("c")]);
// debug all evidence
//Sys.println('');
//for(iEvidence in uut.mem.pairs) {
// Sys.println(iEvidence.convToStr());
//}
Assert.enforce(uut.mem.pairs.length == 1, "must contain the impl seq!");
}
// test if it tries to fullfill a goal
public static function testGoalFullfill1() {
var uut:Executive = new Executive();
var op = new CountOp("^x");
uut.acts.push({mass:1.0, act:op});
{
var pair = new Pair(uut.createStamp());
pair.condops = [new CondOps(new Par([Term.Name("b")]), [buildCallOp("^x")])];
pair.effect = new Par([Term.Name("g")]);
uut.mem.pairs.push(pair);
}
uut.goalSystem.eternalGoals.push(Term.Name("g"));
for(t in 0...150) {
uut.step([Term.Name("b")]);
}
Assert.enforce(op.counter > 0, "op must have been called!");
}
// patricks test from MSC
public static function testGoalFullfill3() {
var uut:Executive = new Executive();
var opX = new CountOp("^x");
var opY = new CountOp("^y");
uut.acts.push({mass:1.0, act:opX});
uut.acts.push({mass:1.0, act:opY});
uut.goalSystem.eternalGoals.push(Term.Name("g"));
uut.step([Term.Name("a")]);
uut.step([buildCallOp("^x")]);
uut.step([Term.Name("b")]);
// flood sequence out of memory
for(i in 0...50) {
uut.step([]);
}
uut.step([Term.Name("b")]);
uut.step([buildCallOp("^y")]);
uut.step([Term.Name("c")]);
uut.step([Term.Name("g")]);
opX.counter = 0;
opY.counter = 0;
// flood sequence out of memory
for(i in 0...50) {
uut.step([]);
}
uut.step([Term.Name("a")]);
uut.step([]);
uut.step([]);
uut.step([]);
uut.step([]);
uut.step([]);
uut.step([Term.Name("b")]);
for(t in 0...100) {
uut.step([]);
}
// debug all evidence
Sys.println('evidence:');
for(iEvidence in uut.mem.pairs) {
Sys.println(iEvidence.convToStr());
}
Assert.enforce(opX.counter > 0 && opY.counter > 0, "ops must have been called!");
}
// test if it tries to fullfill a goal when it is already fullfilled
public static function testGoalFullfillIfSatisfied1() {
var uut:Executive = new Executive();
var op = new CountOp("^x");
uut.acts.push({mass:1.0, act:op});
{
var pair = new Pair(uut.createStamp());
pair.condops = [new CondOps(new Par([Term.Name("b")]), [buildCallOp("^x")])];
pair.effect = new Par([Term.Name("g")]);
uut.mem.pairs.push(pair);
}
uut.goalSystem.eternalGoals.push(Term.Name("g"));
for(t in 0...500) {
uut.step([Term.Name("g"), Term.Name("b")]);
}
Assert.enforce(op.counter == 0, "op must not have been called!");
}
// test if it tries to fullfill a goal when it is already fullfilled
public static function testGoalFullfillIfSatisfied2() {
var uut:Executive = new Executive();
var op = new CountOp("^x");
uut.acts.push({mass:1.0, act:op});
{
var pair = new Pair(uut.createStamp());
pair.condops = [new CondOps(new Par([Term.Name("a")]), [buildCallOp("^x")])];
pair.effect = new Par([Term.Name("b")]);
uut.mem.pairs.push(pair);
}
{
var pair = new Pair(uut.createStamp());
pair.condops = [new CondOps(new Par([Term.Name("b")]), [buildCallOp("^x")])];
pair.effect = new Par([Term.Name("g")]);
uut.mem.pairs.push(pair);
}
uut.goalSystem.eternalGoals.push(Term.Name("g"));
for(t in 0...500) {
uut.step([Term.Name("g"), Term.Name("a")]);
}
Assert.enforce(op.counter == 0, "op must not have been called!");
}
// test forward chainer with implicit length = 2
public static function testGoalFullfillChain2_1() {
var uut:Executive = new Executive();
uut.goalSystem.eternalGoals.push(Term.Name("e"));
var opA = new TermInjOp("^a", uut, Term.Name("b"));
var opB = new TermInjOp("^b", uut, Term.Name("c"));
var opC = new TermInjOp("^c", uut, Term.Name("d"));
var opD = new TermInjOp("^d", uut, Term.Name("e"));
uut.acts.push({mass:1.0, act:opA});
uut.acts.push({mass:1.0, act:opB});
uut.acts.push({mass:1.0, act:opC});
uut.acts.push({mass:1.0, act:opD});
uut.step([Term.Name("a")]);
uut.step([buildCallOp("^a")]);
uut.step([Term.Name("b")]);
// flood sequence out of memory
for(i in 0...50) {
uut.step([]);
}
uut.step([Term.Name("b")]);
uut.step([buildCallOp("^b")]);
uut.step([Term.Name("c")]);
// flood sequence out of memory
for(i in 0...50) {
uut.step([]);
}
uut.step([Term.Name("c")]);
uut.step([buildCallOp("^c")]);
uut.step([Term.Name("d")]);
// flood sequence out of memory
for(i in 0...50) {
uut.step([]);
}
uut.step([Term.Name("d")]);
uut.step([buildCallOp("^d")]);
uut.step([Term.Name("e")]);
// flood sequence out of memory
for(i in 0...50) {
uut.step([]);
}
opA.counter = 0;
opB.counter = 0;
opC.counter = 0;
opD.counter = 0;
uut.step([Term.Name("a")]);
for(t in 0...1000) {
var events = [];
for(ie in opA.queue) {
events.push(ie);
}
for(ie in opB.queue) {
events.push(ie);
}
for(ie in opC.queue) {
events.push(ie);
}
for(ie in opD.queue) {
events.push(ie);
}
opA.queue=[];
opB.queue=[];
opC.queue=[];
opD.queue=[];
uut.step(events);
}
// debug all evidence
Sys.println('');
for(iEvidence in uut.mem.pairs) {
Sys.println(iEvidence.convToStr());
}
Assert.enforce(opD.counter > 0, "ops must have been called!");
}
// see if it picks up a 5 element sequence correctly
public static function dbgSeq5() {
var uut:Executive = new Executive();
var opA = new CountOp("^a");
var opB = new CountOp("^b");
uut.acts.push({mass:1.0, act:opA});
uut.acts.push({mass:1.0, act:opB});
uut.step([Term.Name("a")]);
uut.step([buildCallOp("^a")]);
uut.step([Term.Name("b")]);
uut.step([buildCallOp("^b")]);
uut.step([Term.Name("c")]);
// debug all evidence
Sys.println('');
for(iEvidence in uut.mem.pairs) {
Sys.println(iEvidence.convToStr());
}
}
// see if it executes 5 element sequence correctly
public static function seq5Exec() {
var uut:Executive = new Executive();
{
var p:Pair = new Pair(uut.createStamp());
p.effect = new Par([Term.Name("g")]);
p.condops.push( new CondOps(new Par([Term.Name("a")]), [buildCallOp("^x")]));
p.condops.push( new CondOps(new Par([Term.Name("b")]), [buildCallOp("^y")]));
uut.mem.addPair(p);
}
uut.goalSystem.eternalGoals.push(Term.Name("g"));
var opA = new CountOp("^x");
var opB = new CountOp("^y");
uut.acts.push({mass:1.0, act:opA});
uut.acts.push({mass:1.0, act:opB});
uut.step([Term.Name("a")]);
uut.step([buildCallOp("^x")]);
uut.step([Term.Name("b")]);
uut.step([]);
uut.step([]);
uut.step([]);
uut.step([]);
// debug all evidence
Sys.println('Evidence:');
for(iEvidence in uut.mem.pairs) {
Sys.println(iEvidence.convToStr());
}
Assert.enforce(opB.counter > 0, "ops must have been called!");
}
public static function main() {
//dbgSeq5(); // just for debugging
// was just to test to see if it indeed builds the seq5(sequence of 5 items)
//seq5Exec();
//return;
// short selftests
//testGoalFullfillChain2_1();
testAnticipationConfirm1();
testAnticipationConfirm2();
testTraceEmpty1();
testGoalFullfill1();
testGoalFullfill3(); // MSC patricks test
testGoalFullfillIfSatisfied1();
testGoalFullfillIfSatisfied2();
Sys.println('... all unittests were successful!');
var nExperimentThreads = 4; // number of threads for experiments
var dbgCyclesVerbose = false; // debugging : are cycles verbose?
var alien1RatioDist:IncrementalCentralDistribution = new IncrementalCentralDistribution();
var pong2RatioDist:IncrementalCentralDistribution = new IncrementalCentralDistribution();
var seaquest1RatioDist:IncrementalCentralDistribution = new IncrementalCentralDistribution();
var seaquest1EnemySubDist:IncrementalCentralDistribution = new IncrementalCentralDistribution();
// does run one experiment with the reasoner
function doAlien1ExperimentWithExecutive(executive:Executive, cycles:Int) {
executive.randomActProb = 0.12;
var alien1 = new Alien1(executive);
while(executive.cycle < cycles) {
if(dbgCyclesVerbose) Sys.println('cycl=${executive.cycle}');
// debug anticipations in flight
var dbgAnticipationsInflight = false;
if(dbgAnticipationsInflight && executive.anticipationsInflight.length > 0) {
Sys.println('');
Sys.println('ANTICIPATION inflight:');
for(iAif in executive.anticipationsInflight) {
Sys.println(' ${iAif.origin.convToStr()} deadline=${iAif.deadline}');
}
}
var state:Array<Term> = alien1.emitState();
if(dbgCyclesVerbose) Sys.println('cycl=${executive.cycle} state=${alien1.stateAsStr}');
executive.step(state);
}
// debug all evidence
Logger.log('');
for(iEvidence in executive.mem.pairs) {
Logger.log(iEvidence.convToStr());
}
// add hit ratio to distribution
alien1RatioDist.next(alien1.cntAliensHit / alien1.cntShoots);
// print statistics of world:
alien1.printStats();
}
// does run one experiment with the reasoner
function doPong2ExperimentWithExecutive(executive:Executive, cycles:Int) {
executive.randomActProb = 0.08;
var pong2 = new Pong2(executive);
while(executive.cycle < cycles) {
if(dbgCyclesVerbose) Sys.println('cycl=${executive.cycle}');
// debug anticipations in flight
var dbgAnticipationsInflight = false;
if(dbgAnticipationsInflight && executive.anticipationsInflight.length > 0) {
Sys.println('');
Sys.println('ANTICIPATION inflight:');
for(iAif in executive.anticipationsInflight) {
Sys.println(' ${iAif.origin.convToStr()} deadline=${iAif.deadline}');
}
}
var state:Array<Term> = pong2.emitState();
if(dbgCyclesVerbose) Sys.println('cycl=${executive.cycle} state=${pong2.stateAsStr}');
executive.step(state);
pong2.simulate();
}
// debug all evidence
Logger.log('');
for(iEvidence in executive.mem.pairs) {
Logger.log(iEvidence.convToStr());
}
// add hit ratio to distribution
pong2RatioDist.next(pong2.hits / pong2.misses);
// print statistics of world:
pong2.printStats();
}
function doSeaquestExperimentWithExecutive(executive:Executive, cycles:Int) {
executive.randomActProb = 0.04;
var seaquest = new Seaquest1(executive);
while(executive.cycle < cycles) {
if(dbgCyclesVerbose) Sys.println('cycl=${executive.cycle}');
// debug anticipations in flight
var dbgAnticipationsInflight = false;
if(dbgAnticipationsInflight && executive.anticipationsInflight.length > 0) {
Sys.println('');
Sys.println('ANTICIPATION inflight:');
for(iAif in executive.anticipationsInflight) {
Sys.println(' ${iAif.origin.convToStr()} deadline=${iAif.deadline}');
}
}
if(false && executive.cycle % 15 == 0) { // do we interactivly debug seaquest?
seaquest.consoleVis();
Sys.sleep(0.03);
}
var state:Array<Term> = seaquest.emitState();
if(dbgCyclesVerbose) Sys.println('cycl=${executive.cycle} state=${seaquest.stateAsStr}');
executive.step(state);
seaquest.simulate();
}
// debug all evidence
Logger.log('');
for(iEvidence in executive.mem.pairs) {
Logger.log(iEvidence.convToStr());
}
// add hit ratio to distribution
seaquest1RatioDist.next(seaquest.cntEnemyHit / seaquest.cntShoots);
seaquest1EnemySubDist.next(seaquest.cntEnemyHit);
// print statistics of world:
seaquest.printStats();
}
//trace(Par.checkSubset(new Par([new Term("a")]), new Par([new Term("a")])));
var numberOfExperiments = 10;
var nActiveExperimentThreads = 0; // how many threads are active for the experiment?
var nActiveExperimentThreadsLock:sys.thread.Mutex = new sys.thread.Mutex();
var numberOfDoneExperiments = 0; // how many experiments were done until now?
// do experiments with executive/reasoner
while(numberOfDoneExperiments < numberOfExperiments) {
// wait as long as there are no available workthreads
/*
while(true) {
nActiveExperimentThreadsLock.acquire();
var activeThreads:Int = nActiveExperimentThreads;
nActiveExperimentThreadsLock.release();
if (activeThreads < nExperimentThreads) {
break;
}
Sys.sleep(0.08);
}
*/
nActiveExperimentThreadsLock.acquire();
if (nActiveExperimentThreads >= nExperimentThreads) {
nActiveExperimentThreadsLock.release();
continue; // retry
}
nActiveExperimentThreadsLock.release();
Sys.println('start thread nactive=${nActiveExperimentThreads}');
nActiveExperimentThreadsLock.acquire();
nActiveExperimentThreads++;
nActiveExperimentThreadsLock.release();
#if (target.threaded)
sys.thread.Thread.create(() -> {
var cyclesAlien2:Int = 30000;
var cyclesPong2:Int = 5*35001;//150000;
var executive:Executive = new Executive();
//doAlien1ExperimentWithExecutive(executive, cyclesAlien2);
var executive:Executive = new Executive();
doPong2ExperimentWithExecutive(executive, cyclesPong2);
var executive:Executive = new Executive();
//doSeaquestExperimentWithExecutive(executive, 30000);
numberOfDoneExperiments++; // bump counter
nActiveExperimentThreadsLock.acquire();
nActiveExperimentThreads--;
nActiveExperimentThreadsLock.release();
Sys.println('alien1 hit ratio mean=${alien1RatioDist.mean} variance=${alien1RatioDist.calcVariance()} n=${alien1RatioDist.n}');
Sys.println('pong2 ratio mean=${pong2RatioDist.mean} variance=${pong2RatioDist.calcVariance()} n=${pong2RatioDist.n}');
});
#end
}
Sys.println('alien1 hit ratio mean=${alien1RatioDist.mean} variance=${alien1RatioDist.calcVariance()} n=${alien1RatioDist.n}');
Sys.println('pong2 ratio mean=${pong2RatioDist.mean} variance=${pong2RatioDist.calcVariance()} n=${pong2RatioDist.n}');
Sys.println('seaquest1 enemy sub shot mean=${seaquest1EnemySubDist.mean} variance=${seaquest1EnemySubDist.calcVariance()} n=${seaquest1EnemySubDist.n}');
}
}
// op for testing if op was called
// used for self-tests, unittests, etc.
class CountOp extends Act {
public var counter:Int = 0;
public function new(name:String) {
super(name);
}
public override function exec(args:Array<Term>) {
counter++;
}
}
// injects a term on call
class TermInjOp extends Act {
public var uut:Executive;
public var term:Term;
public var counter:Int = 0;
public var queue:Array<Term> = [];
public function new(name:String, uut, term) {
super(name);
this.uut = uut;
this.term = term;
}
public override function exec(args:Array<Term>) {
queue.push(TermUtils.cloneShallow(term));
counter++;
}
}
// action for the world
class Pong1Act extends Act {
public var w:Pong1;
public var delta:Float;
public function new(name:String, w:Pong1, delta:Float) {
super(name);
this.delta = delta;
this.w = w;
}
public override function exec(args:Array<Term>) {
w.posX += delta;
w.posX = Math.max(0.0, w.posX);
w.posX = Math.min(1.0, w.posX);
}
}
// pong world where the bat moves only when a action is done
class Pong1 {
public var posX:Float = 0.35; // position of the agent
public var posAlien:Float = 0.5; // position of the alien
public var executive:Executive;
public var stateAsStr:String = ""; // current state as string for debugging
public function new(executive) {
this.executive = executive;
this.executive.acts.push({mass:1.0, act:new Pong1Act("^l", this, -0.1)});
this.executive.acts.push({mass:1.0, act:new Pong1Act("^r", this, 0.1)});
this.executive.goalSystem.eternalGoals.push(Term.Name("c")); // try to keep in center
}
// returns the state of the world
public function emitState(): Array<Term> {
var res = [];
var diff: Float = posX - posAlien;
if (Math.abs(diff) < 0.1) {
stateAsStr = "c";
res.push(Term.Name("c"));
}
else if(diff > 0.0) {
stateAsStr = "r";
res.push(Term.Name("r"));
}
else {
stateAsStr = "l";
res.push(Term.Name("l"));
}
return res;
}
}
// action for the world
class Pong2Act extends Act {
public var w:Pong2;
public var delta:Float;
public function new(name:String, w:Pong2, delta:Float) {
super(name);
this.delta = delta;
this.w = w;
}
public override function exec(args:Array<Term>) {
w.speed = delta;
}
}
// pong world where the bat moves continiously and stop is available
class Pong2 {
public var batPosX:Float = 0.35; // position of the agent
public var speed:Float = 0.0; // speed of the bat
public var posBallX:Float = 0.5; // position of the alien
public var posBallY:Float = 0.5; // position of the alien
public var velBallX:Float = 0.034;
public var velBallY:Float = 0.04;
public var executive:Executive;
public var stateAsStr:String = ""; // current state as string for debugging
public var misses = 0;
public var hits = 0;
public var isGood = false;
public function new(executive) {
this.executive = executive;
this.executive.acts.push({mass:1.0, act:new Pong2Act("^l", this, -0.05)});
this.executive.acts.push({mass:1.0, act:new Pong2Act("^r", this, 0.05)});
this.executive.acts.push({mass:1.0, act:new Pong2Act("^stop", this, 0.0)});
this.executive.goalSystem.eternalGoals.push(Term.Name("g")); // try to keep in center
}
// print statistics
public function printStats() {
Sys.println('pong2 misses = $misses');
Sys.println('pong2 hits = $hits');
Sys.println('hit ratio = ${hits / misses}');
}
// returns the state of the world
public function emitState(): Array<Term> {
var res = [];
stateAsStr = "";
var diff: Float = posBallX - batPosX;
if (Math.abs(diff) < 0.1) {
stateAsStr = "c";
res.push(Term.Name("c"));
}
else if(diff > 0.0) {
stateAsStr = "r";
res.push(Term.Name("r"));
}
else if(diff < 0.0){
stateAsStr = "l";
res.push(Term.Name("l"));
}
if (isGood) {
stateAsStr += " g";
res.push(Term.Name("g"));
}
return res;
}
// simulates world
public function simulate() {
isGood = false;
batPosX += speed;
batPosX = Math.max(0.0, batPosX);
batPosX = Math.min(1.0, batPosX);
posBallX += velBallX;
posBallY += velBallY;
//trace('pong2 pos = <$posBallX, $posBallY>');
if (posBallY < 0.0) {
var diff: Float = posBallX - batPosX;
var hitBat = Math.abs(diff) < 0.1;
if (hitBat) {
hits++;
}
else {
misses++;
}
if (hitBat) {
isGood = true;
velBallY = Math.abs(velBallY);
}
else {
// respawn ball
posBallX = Math.random();
posBallY = Math.random();
velBallX = (Math.random() * 2.0 - 1.0) * 0.05;
velBallY = (Math.random() * 2.0 - 1.0) * 0.05;
}
}
if (posBallY > 1.0) {
velBallY = -Math.abs(velBallY);
}
if (posBallX < 0.0) {
velBallX = Math.abs(velBallX);
}
else if(posBallX > 1.0) {
velBallX = -Math.abs(velBallX);
}
}
}
// action for the world
class Alien1Act extends Act {
public var w:Alien1;
public var delta:Float;
public function new(name:String, w:Alien1, delta:Float) {
super(name);
this.delta = delta;
this.w = w;
}
public override function exec(args:Array<Term>) {
w.posX += delta;
w.posX = Math.max(0.0, w.posX);
w.posX = Math.min(1.0, w.posX);
if (this.name == "^s") { // is shoot action?
w.cntShoots++; // bump statistics
for(idx in 0...w.posAliens.length) {
var diff: Float = w.posX - w.posAliens[idx];
if (Math.abs(diff) < 0.06*1.5) { // did we hit a alien?
w.state.push(Term.Name('s$idx')); // shot down
w.posAliens[idx] = Math.random(); // respawn at random position
w.cntAliensHit++; // bump statistics
break; // break because the shot was absorbed by one alien and can't hit another
}
}
}
}
}
// alien invasion world where aliens move around and where the player can move only incrementally
class Alien1 {
public var posX:Float = 0.35; // position of the agent
public var posAliens:Array<Float> = [0.5, 0.7]; // position of the aliens
public var executive:Executive;
public var stateAsStr:String = ""; // current state as string for debugging
public var state:Array<Term> = [];
public var cntShoots:Int = 0; // statistics - how many shots were fired
public var cntAliensHit:Int = 0; // statistics - how many aliens were hit by shots
// print statistics
public function printStats() {
Sys.println('shots fired = $cntShoots');
Sys.println('aliens hit = $cntAliensHit');
Sys.println('hit ratio = ${cntAliensHit / cntShoots}');
}
public function new(executive) {
this.executive = executive;
this.executive.acts.push({mass:1.0, act:new Alien1Act("^l", this, -0.06)});
this.executive.acts.push({mass:1.0, act:new Alien1Act("^r", this, 0.06)});
{
var shootAct = new Alien1Act("^s", this, 0.0);
shootAct.refractoryPeriod = 4; // don't let the agent spam the shot button
this.executive.acts.push({mass:1.0, act:shootAct});
}
this.executive.goalSystem.eternalGoals.push(Term.Name("s0")); // shoot down
this.executive.goalSystem.eternalGoals.push(Term.Name("s1")); // shoot down
}
// returns the state of the world
public function emitState(): Array<Term> {
var res = state;
stateAsStr = "";
for(idx in 0...posAliens.length) {
var diff: Float = posX - posAliens[idx];
if (Math.abs(diff) < 0.1) {
stateAsStr += ' c$idx';
res.push(Term.Name('c$idx'));
}
else if(diff > 0.0) {
stateAsStr += ' r$idx';
res.push(Term.Name('r$idx'));
}
else {
stateAsStr += ' l$idx';
res.push(Term.Name('l$idx'));
}
}
state = [];
return res;
}
}
class Seaquest1Act extends Act {
public var w:Seaquest1;
public var deltaX:Float;
public var deltaY:Float;
public function new(name:String, w:Seaquest1, deltaX:Float, deltaY:Float) {
super(name);
this.deltaX = deltaX;
this.deltaY = deltaY;
this.w = w;
}
public override function exec(args:Array<Term>) {
w.posX += deltaX;
w.posY += deltaY;
w.posX = Math.max(0.0, w.posX);
w.posX = Math.min(1.0, w.posX);
w.posY = Math.max(0.0, w.posY);
w.posY = Math.min(1.0, w.posY);
if (this.name == "^s") { // is shoot action?
w.cntShoots++; // bump statistics
w.actShoot = true;
}
if (this.name == "^l") {
w.dir = -1;
}
else if(this.name == "^r") {
w.dir = 1;
}
}
}
class Entity {
public var type:String;
public var posX:Float = 0.0;
public var posY:Float = 0.0;
public var velX:Float = 0.0;
public var velY:Float = 0.0;
public function new(type) {
this.type=type;
}
public function step() {
posX+=velX;
posY+=velY;
}
}
// TODO< add direction of submarine and change it when ever ^r,^l is done, also propagate it as state to reasoner >
class Seaquest1 {
public var posX:Float = 0.35; // position of the agent
public var posY:Float = 0.5; // position of the agent
public var dir:Int = 1; // "look" direction of submarine
public var actShoot:Bool = false; // shoot in the next timestep?
public var entities:Array<Entity> = [];
public var executive:Executive;
public var stateAsStr:String = ""; // current state as string for debugging
public var state:Array<Term> = [];
public var cntShoots:Int = 0; // statistics - how many shots were fired
public var cntEnemyHit:Int = 0; // statistics - how many enemy submarines were hit
public var cntFishHit:Int = 0; // statistics - how many enemy fishes were hit
// print statistics
public function printStats() {
Sys.println('shots fired = $cntShoots');
Sys.println('enemy hit = $cntEnemyHit');
Sys.println('hit ratio = ${cntEnemyHit / cntShoots}');
}