-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ.java
More file actions
1110 lines (927 loc) · 31 KB
/
Q.java
File metadata and controls
1110 lines (927 loc) · 31 KB
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
/*
Name: Adam Johnson
Course: 421 - AI
Assignment: 5 Q learning
Due: 11/21/2016
*/
import java.io.*;
import java.util.*;
public class Q{
public static void main(String[] args)throws InterruptedException{
//first delete all the old result files
int count = 0;
boolean running = true;
do{
File del = new File("output/results" + count + ".txt");
if(del.exists()){
del.delete();
//System.out.println("Deleted : " + del.getName());
} else {
running = false;
//System.out.println("FFF");
}
count++;
} while (running);
File f;
try{
//take in the data file from args[0]
f = new File(args[0]);
//after reading in the file create the objects
Agent a = processFile(f);
//a.map().printMap(new MyPoint(0,0));
//Movement is implemented in this run function
//The run function handles movement as well as a set number of
//epochs currently the only way to change epochs is by changing the
//hard coded numberti
a.run();
} catch (FileNotFoundException e){
System.out.println("The file does not exists");
}
}
public static Agent processFile(File f) throws FileNotFoundException{
Scanner fc = new Scanner(f);
//put the control variables into a string
String variables = fc.nextLine();
//put the escape location into a string
String escape = fc.nextLine();
//put the pony variables into a string
String ponies = fc.nextLine();
//put the series of obstacles into a string
String obstacles = fc.nextLine();
//put the series of trolls into a string
String trolls = fc.nextLine();
//open the scanner on variables
fc = new Scanner(variables);
//go through the variables
int n = fc.nextInt();
int nTrolls = fc.nextInt();
int nPonies = fc.nextInt();
//go through the escape
fc = new Scanner(escape);
MyPoint escapeLoc = new MyPoint(fc.nextInt(), fc.nextInt());
//go through the ponies
fc = new Scanner(ponies);
ArrayList<Pony> ponyLoc = new ArrayList<>();
for(int i = 0; i < nPonies; i++){
int x = fc.nextInt();
int y = fc.nextInt();
ponyLoc.add( new Pony(new MyPoint(x, y)));
}
//go through the obstacles
fc = new Scanner(obstacles);
ArrayList<Obstacle> obstacleLoc = new ArrayList<>();
while(fc.hasNext()){
int x = fc.nextInt();
int y = fc.nextInt();
MyPoint temp = new MyPoint(x,y);
obstacleLoc.add( new Obstacle(temp));
}
//go through the trolls
fc = new Scanner(trolls);
ArrayList<Troll> trollLoc = new ArrayList<>();
for(int i = 0; i < nTrolls; i++){
int x = fc.nextInt();
int y = fc.nextInt();
MyPoint temp = new MyPoint(x,y);
Troll newTroll = new Troll(temp);
trollLoc.add( newTroll);
}
//gather the input parameters
fc = new Scanner(System.in);
//return a new worldmap
WorldMap m = new WorldMap(trollLoc, ponyLoc, obstacleLoc, n, escapeLoc,
getAlpha(fc), getGamma(fc), getQ(fc));
return new Agent(m);
}
private static double getAlpha(Scanner sc){
System.out.print("Enter alpha: ");
while(!sc.hasNextDouble()){
System.out.print("Enter alpha: ");
sc.next();
}
return sc.nextDouble();
}
private static double getGamma(Scanner sc){
System.out.print("Enter gamma: ");
while(!sc.hasNextDouble()){
System.out.print("Enter gamma: ");
sc.next();
}
return sc.nextDouble();
}
private static double getQ(Scanner sc){
System.out.print("Enter q: ");
while(!sc.hasNextDouble()){
System.out.print("Enter q: ");
sc.next();
}
return sc.nextDouble();
}
}
class Troll{
MyPoint location;
public Troll(MyPoint p){
location = p;
}
public boolean equals(Object other){
if(other instanceof Troll){
Troll i = (Troll) other;
if((i.location.equals(location))){
return true;
}
}
return false;
}
public String toString(){
return "T";
}
}
class Pony {
MyPoint location;
public Pony(MyPoint p){
location = p;
}
public boolean equals(Object other){
if(other instanceof Pony){
Pony i = (Pony) other;
if((i.location.equals(location))){
return true;
}
}
return false;
}
public String toString(){
return "P";
}
}
class Obstacle {
MyPoint location;
public Obstacle(MyPoint p){
location = p;
}
public boolean equals(Object other){
if(other instanceof Obstacle){
Obstacle i = (Obstacle) other;
if((i.location.equals(location))){
return true;
}
}
return false;
}
public String toString(){
return "#";
}
}
class WorldMap{
public static int n = 0;
private ArrayList<Troll> trolls;
private ArrayList<Pony> ponies;
private ArrayList<Obstacle> obstacles;
private int size;
private MyPoint escape;
private State[][] map;
private double alpha;
private double gamma;
private double q;
public WorldMap(ArrayList<Troll> t, ArrayList<Pony> p, ArrayList<Obstacle> a, int s, MyPoint esc ,double al, double g, double q){
trolls = t;
ponies = p;
obstacles = a;
size = s;
map = new State[size][size];
escape = esc;
alpha = al;
gamma = g;
this.q = q;
initMap();
}
public State getStart(){
Random rand = new Random();
int x = rand.nextInt(size);
int y = rand.nextInt(size);
boolean run =true;
do{
x = rand.nextInt(size);
y = rand.nextInt(size);
run = false;
for(Obstacle o : obstacles){
if(o.location.equals(new MyPoint(x, y)))
run = true;
}
for(Troll o : trolls){
if(o.location.equals(new MyPoint(x, y)))
run = true;
}
if(escape.equals(new MyPoint(x,y)))
run = true;
} while(run);
map[x][y].setTaken();
return map[x][y];
}
private void initMap(){
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
map[i][j] = new State(new MyPoint(i, j));
}
}
Action nw = null;
Action n = null;
Action ne = null;
Action e = null;
Action se = null;
Action s = null;
Action sw = null;
Action w = null;
//go through each location and assign actions to the states
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
MyPoint mp = new MyPoint(i,j);
//if we go out of bounds we self reference action
if(i - 1 < 0 || j + 1 >= size){
//nw = new Action(map[i][j]);
} else {
Boolean b = true;
MyPoint op = new MyPoint( i - 1, j + 1);
//check if the x,y pair goes to an obstacle
for(Obstacle it : obstacles){
//if we find an obstacle at the point
if(it.equals(new Obstacle(op))){
b = false;
}
}
if(b){
nw = new Action(map[i-1][j+1], alpha, gamma, q);
} else {
//nw = new Action(map[i][j]);
}
}
//setup north
if(j + 1 >= size){
//n = new Action(map[i][j]);
} else {
Boolean b = true;
MyPoint op = new MyPoint( i , j + 1);
//check if the x,y pair goes to an obstacle
for(Obstacle it : obstacles){
//if we find an obstacle at the point
if(it.equals(new Obstacle(op))){
b = false;
}
}
if(b){
n = new Action(map[i][j+1], alpha, gamma, q);
} else {
//n = new Action(map[i][j]);
}
}
//setup northeast
if(i + 1 >= size || j + 1 >= size){
// ne = new Action(map[i][j]);
} else {
Boolean b = true;
MyPoint op = new MyPoint( i + 1, j + 1);
//check if the x,y pair goes to an obstacle
for(Obstacle it : obstacles){
//if we find an obstacle at the point
if(it.equals(new Obstacle(op))){
b = false;
}
}
if(b){
ne = new Action(map[i+1][j+1], alpha, gamma, q);
} else {
// ne = new Action(map[i][j]);
}
}
//setup east
if(i + 1 >= size){
//e = new Action(map[i][j]);
} else {
Boolean b = true;
MyPoint op = new MyPoint( i + 1 , j);
//check if the x,y pair goes to an obstacle
for(Obstacle it : obstacles){
//if we find an obstacle at the point
if(it.equals(new Obstacle(op))){
b = false;
}
}
if(b){
e = new Action(map[i+1][j], alpha, gamma, q);
} else {
//e = new Action(map[i][j]);
}
}
//setup southeast
if(i + 1 >= size || j - 1 < 0){
//se = new Action(map[i][j]);
} else {
Boolean b = true;
MyPoint op = new MyPoint( i + 1, j - 1);
//check if the x,y pair goes to an obstacle
for(Obstacle it : obstacles){
//if we find an obstacle at the point
if(it.equals(new Obstacle(op))){
b = false;
}
}
if(b){
se = new Action(map[i+1][j-1], alpha, gamma, q);
} else {
//se = new Action(map[i][j]);
}
}
//setup south
if(j - 1 < 0){
//s = new Action(map[i][j]);
} else {
Boolean b = true;
MyPoint op = new MyPoint( i , j - 1);
//check if the x,y pair goes to an obstacle
for(Obstacle it : obstacles){
//if we find an obstacle at the point
if(it.equals(new Obstacle(op))){
b = false;
}
}
if(b){
s = new Action(map[i][j-1], alpha, gamma, q);
} else {
//s = new Action(map[i][j]);
}
}
//setup southwest
if(i - 1 < 0 || j -1 < 0){
//sw = new Action(map[i][j]);
} else {
Boolean b = true;
MyPoint op = new MyPoint( i - 1, j - 1);
//check if the x,y pair goes to an obstacle
for(Obstacle it : obstacles){
//if we find an obstacle at the point
if(it.equals(new Obstacle(op))){
b = false;
}
}
if(b){
sw = new Action(map[i-1][j-1], alpha, gamma, q);
} else {
//sw = new Action(map[i][j]);
}
}
//setup west
if(i - 1 < 0){
//w = new Action(map[i][j]);
} else {
Boolean b = true;
MyPoint op = new MyPoint( i - 1, j );
//check if the x,y pair goes to an obstacle
for(Obstacle it : obstacles){
//if we find an obstacle at the point
if(it.equals(new Obstacle(op))){
b = false;
}
}
if(b){
w = new Action(map[i-1][j], alpha, gamma, q);
} else {
// w = new Action(map[i][j]);
}
}
//at this point all directions are setup
ArrayList<Action> actions = new ArrayList<>();
if(nw != null)
actions.add(nw);
if(n != null)
actions.add(n);
if(ne != null)
actions.add(ne);
if(e != null)
actions.add(e);
if(se != null)
actions.add(se);
if(s != null)
actions.add(s);
if(sw != null)
actions.add(sw);
if(w != null)
actions.add(w);
map[i][j].initActions(actions);
//reset the actions;
nw = null;
n = null;
ne = null;
e = null;
se = null;
s = null;
sw = null;
w = null;
}
}
resetContains();
}
public void resetContains(){
//set all taken to false
for(int i = 0; i < size; i ++){
for(int j = 0; j < size; j++){
map[j][i].resetTaken();
}
}
//go through each state and flip their contains
for(Pony t : ponies){
int x = t.location.x;
int y = t.location.y;
map[x][y].setPony(true);
}
for(Troll t : trolls){
int x = t.location.x;
int y = t.location.y;
map[x][y].setTroll(true);
}
for(Obstacle t : obstacles){
int x = t.location.x;
int y = t.location.y;
if(x != -1)
map[x][y].setObstacle(true);
}
//set the escape
map[escape.x][escape.y].setEscape(true);
}
public State getState(Action a){
a.result.setTaken();
return a.result;
}
public double getReward(State s){
//find out what we landed on
MyPoint loc = s.pointData();
//check this point against trolls
if(s.troll){
return -15;
}
//check this point against ponies
if(s.pony){
s.setPony(false);
return 10;
}
if(escape.equals(loc)){
return 15;
}
return 2;
}
public State[][] getStateMap(){
return map;
}
public void printMap(MyPoint agent){
try{
File writeTo = new File("output/results" + n + ".txt");
//create the file if it does not exist
if(!writeTo.exists()){
writeTo.createNewFile();
}
//Here true is to append the content to file
FileWriter fw = new FileWriter(writeTo,true);
//BufferedWriter writer give better performance
BufferedWriter bw = new BufferedWriter(fw);
for(int i = size - 1; i >= 0; i--)
bw.write("#");
bw.write("##\n");
for(int i = size - 1; i >= 0; i--){
bw.write("#");
for(int j = 0; j < size; j++){
if(!agent.equals(map[j][i].actualLocation)){
bw.write(getSymbol(map[j][i]));
} else {
bw.write("A");
}
}
bw.write("#\n");
}
bw.write("#");
for(int i = 0; i <= size - 1; i++)
bw.write("#");
bw.write("#\n");
bw.write("\n");
//Closing BufferedWriter Stream
bw.close();
} catch (FileNotFoundException e){
System.exit(1);
} catch (IOException e2){
System.exit(1);
}
}
public void printEnd(double reward){
try{
File writeTo = new File("output/results" + n + ".txt");
//create the file if it does not exist
if(!writeTo.exists()){
writeTo.createNewFile();
}
//Here true is to append the content to file
FileWriter fw = new FileWriter(writeTo,true);
//BufferedWriter writer give better performance
BufferedWriter bw = new BufferedWriter(fw);
//print out the total Reward
bw.write("Total reward:" + reward);
bw.write("\n Pony rescue ratio: " + (ponies.size() - notRescued() ) + "/" + ponies.size());
//Closing BufferedWriter Stream
bw.close();
n++;
} catch (FileNotFoundException e){
System.exit(1);
} catch (IOException e2){
System.exit(1);
}
}
private String getSymbol(State s){
return s.symbol;
}
private int notRescued(){
int r = 0;
for(int i = 0; i <size; i ++){
for(int j = 0; j <size; j ++){
if(map[j][i].pony)
r++;
}
}
return r;
}
}
class State{
ArrayList<Action> actions;
MyPoint actualLocation;
String symbol;
boolean obstacle;
boolean troll;
boolean pony;
boolean escape;
boolean taken;
double r;
int visited;
public State(MyPoint p){
actualLocation = p;
initialSetup();
}
private void initialSetup(){
symbol = "-";
troll = false;
pony = false;
escape = false;
taken = false;
}
public void initActions(ArrayList<Action> a){
actions = a;
visited = -1;
updateR();
}
public MyPoint pointData(){
return actualLocation;
}
public String toString(){
return actualLocation.toString();
}
public void setTroll(boolean b){
troll = b;
setSymbol();
}
public void setPony(boolean b){
pony = b;
setSymbol();
}
public void updateR(){
double highest = actions.get(0).q;
//go through each of the actions and determine the highest q
for(Action a : actions){
if(highest < a.q){
highest = a.q;
}
}
r = highest;
visited++;
}
public void setObstacle(boolean b){
obstacle = b;
setSymbol();
}
public void setEscape(boolean b){
escape = b;
setSymbol();
}
public void setTaken(){
taken = true;
setSymbol();
}
public void resetTaken(){
taken = false;
setSymbol();
}
private void setSymbol(){
//always want obstacle to be set first
if(obstacle){
symbol = "#";
return;
}
//then we want troll on top no matter what
if(troll){
symbol = "T";
return;
}
//then pony
if(pony){
symbol = "P";
return;
}
//then taken
if(taken){
symbol = "X";
return;
}
//then escape
if(escape){
symbol = "E";
return;
}
//if nothing is here
symbol = "-";
}
}
class Action{
public int z = 0;
State result;
double q;
double alpha;
double gamma;
public Action(State r){
this(r, .5, .5, 0);
}
public Action(State r, double a, double g, double q){
result = r;
alpha = a;
gamma = g;
q = 0;
}
public String toString(){
return result.pointData().toString();
}
public void update(Double d){
double temp = q;
q = q + getAlpha() * ( d + (gamma * result.r) - q );
if(Math.abs(temp - q) < .000_000_000_000_001){
z++;
if(z == 1000){
System.out.println("Converged");
}
return;
}
z = 0;
}
private double getAlpha(){
//comment out this line if you want to use variable learning rate
//if(true) return alpha;
if (alpha - .01 * result.visited < .01){
return .01;
}
return alpha - .01 * result.visited;
}
}
class Agent {
WorldMap wm;
public Agent(WorldMap a){
wm = a;
}
public void run() throws InterruptedException{
//get start space
int run = 0;
int count = 0;
double highest = 0;
while(count != 10000){
State start = wm.getStart();
double t = 0;
if(!start.troll && !start.escape)
t = oneEpoch(start);
else{
//wm.printMap(start.actualLocation);
if(start.escape){
t = 15;
} else {
t = -15;
}
}
if(t == 15){
;
} else if(t > highest){
highest = t;
run = count;
}
count++;
//wm.printEnd(t);
wm.resetContains();
}
//the agent not follows the learned policy
State start = wm.getStart();
this.exploit(start);
System.out.println("The highest reward was : " + highest + " from run " +
run);
}
private double oneEpoch(State start) throws InterruptedException{
//print the map before hand
//wm.printMap(start.actualLocation);
//Thread.sleep(1000);
//System.out.println("we got the start");
double sum = 0;
int step = 0;
boolean running = true;
while(running){
Action picked = null;
double denom = 0;
//evaluate each action from the start
for(Action a : start.actions){
//get the total for each action
denom += Math.exp(a.q/10000);
}
//determine if we explore or if we choose highest q
if(Math.random() >= .9){
//randomly pick an action
double summ = 0;
Random r = new Random();
double p = r.nextDouble() * denom;
boolean notPicked = true;
for(Action a : start.actions){
//get the total for each action
summ += Math.exp(a.q/10000);
if(summ >= p && notPicked){
picked = a;
notPicked = false;
}
}
} else {
Action highest = null;
for(Action a : start.actions){
if(highest == null){
highest = a;
} else if(a.q > highest.q){
highest = a;
} else if(a.q == highest.q){
if(Math.random() > .5){
highest = a;
}
}
}
picked = highest;
}
State temp = start;
//send action to get a new state back to the mothership
start = wm.getState(picked);
//receive reward
double reward = wm.getReward(start);
//update the action taken with the reward value
picked.update(reward);
sum+= reward;
//after updating the Q value on the action go back to the previous
//state and update the r value
temp.updateR();
step++;
//check if reward is -15 or 15
if(reward == 15){
//System.out.println("FOUND THE ESCAPE");
running = false;
} else if(reward == -15){
//System.out.println("KILLED BY DANNY DIVITO");
running = false;
}
//print out the map at the new start
//Thread.sleep(1000);
}
//System.out.println(sum);
//wm.printMap(start.actualLocation);
return sum;
}
///exploit
private double exploit(State start) throws InterruptedException{
//print the map before hand
wm.printMap(start.actualLocation);
//Thread.sleep(1000);
//System.out.println("we got the start");
double sum = 0;
int step = 0;
boolean running = true;
ArrayList<State> visited = new ArrayList<>();
while(running){
Action picked = null;
Action highest = null;
for(Action a : start.actions){
/*
if(visited.contains(a.result)){
continue;
}
*/
if(highest == null ){
highest = a;
} else if(a.q > highest.q ){
highest = a;
}
/*
if(a.q == highest.q ){
if(Math.random() > .5){
highest = a;
}
}
*/
}
picked = highest;
visited.add(picked.result);
State temp = start;