forked from berickcook/AIRIS_Public
-
Notifications
You must be signed in to change notification settings - Fork 1
/
airis_stable.py
2107 lines (1727 loc) · 107 KB
/
airis_stable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import copy
import numpy as np
import heapq
import random
from operator import itemgetter
from datetime import datetime
from model import Model
from other_useful_functions import *
class AIRIS(object):
def __init__(self, vis_env, aux_env, action_space, action_output_list):
# clear logfile
if DEBUG_WITH_LOGFILE:
open(DEBUG_LOGFILE_PATH, 'w').close()
pprint('initializing AIRIS ...', new_line_start=True, draw_line=False)
start_time = datetime.now()
# visual and non-visual (auxiliary)
# environment BEFORE the action is taken
self.prior_vis_env = np.array(vis_env, dtype=np.float32)
self.prior_aux_env = np.array(aux_env, dtype=np.float32)
# visual and non-visual
# environment AFTER the action is taken
self.posterior_vis_env = np.array(vis_env, dtype=np.float32)
self.posterior_aux_env = np.array(aux_env, dtype=np.float32)
# load existing knowledge or create a new knowledge dictionary
try:
self.load_knowledge()
self.condition_id = self.knowledge['last condition id'] + 1
except:
self.knowledge = {}
self.knowledge['action set'] = set()
self.condition_id = 0 # id of condition in the knowledge
# list of all models AIRIS has made
self.current_model_index = None
self.models = [0]
# set of all unique visual and non-visual values ever seen since birth
self.vis_global_set = set()
self.focus_global_set = set()
self.not_focus_global_set = set()
self.aux_global_set = set()
# list of all possible actions AIRIS can take
self.action_space = action_space
# output range of each action [min, max, increment size]
self.action_output_list = action_output_list
self.action_plan = [] # sequence of planned actions
self.action_plan_depth_limit = 50
self.goal_type_default = 'Random'
self.goal_type = 'Random'
self.goal_action = None
self.goal_output = None
self.goal_source = {
'value': None,
'x': None, # x of goal value relative to focus value
'y': None, # y of goal value relative to focus value
'i': None # i is for if the goal_source is an auxiliary input
}
self.goal_condition = None
self.goal_value = None
# lists of visual and auxiliary changes in the env from prior to posterior
self.vis_change_list = []
self.aux_change_list = []
self.vis_change_list_prev = []
self.posterior_focus_value = None #
self.vis_change_index = None # index of the visual change we're focusing on
self.aux_change_index = None
# working prediction(s) of what the visual input will be after a given action and visual and aux inputs
self.env_count = {}
self.env_count_list = []
self.worst_set = set()
self.display_hold = False
self.display_plan = [0]
pprint('initialization complete. duration: %s' % (datetime.now() - start_time))
def print_mind(self, indent=DEFAULT_INDENT, num_indents=0,
new_line_start=False, new_line_end=False,
draw_line=DEFAULT_DRAW_LINE,
prior=True, post=True, focus_value=True,
models=True, knowledge=True, best_condition_id=True,
global_sets=True, current_model_index=True,
goal=True, action_plan=True, change_lists=True):
# print the environment variables of AIRIS's mind
if DEBUG_WITH_CONSOLE:
pprint('/--------------------------------------------------------\\')
if prior:
pprint('ACTION PRIOR:')
print_vis_env(self.prior_vis_env, title='Visual Environment:')
pprint('Auxiliary Environment')
pprint(self.prior_aux_env.astype(int))
if post:
pprint('\nACTION POSTERIOR:')
print_vis_env(self.posterior_vis_env, title='Visual Environment:')
pprint('Auxiliary Environment')
pprint(self.posterior_aux_env.astype(int))
if change_lists:
self.print_change_lists()
if focus_value:
pprint('focus_value:\t\t\t%s' % self.models[self.current_model_index].focus_value)
if global_sets:
self.print_global_sets()
if current_model_index:
pprint('Current Model Index:\t\t%s' % self.current_model_index)
if models:
self.print_models()
if knowledge:
pprint('Knowledge:')
pprint(self.knowledge)
self.print_knowledge(indent=indent, num_indents=num_indents, draw_line=draw_line)
# pass # tbd ... how do we print this in a concise way? this might be where a gui comes in handy
if goal:
pprint('Goal Type:\t%s' % self.goal_type)
pprint('Goal Action:\t%s' % self.goal_action)
pprint('Goal Output:\t%s' % self.goal_output)
self.print_goal_source()
if action_plan:
pprint('Action Plan:\n%d actions' % len(self.action_plan))
for goal_action, goal_output in self.action_plan:
pprint(goal_action, goal_output)
pprint('\\--------------------------------------------------------/\n')
def print_models(self, new_line_start=False, new_line_end=False):
if DEBUG_WITH_CONSOLE or DEBUG_WITH_LOGFILE:
if new_line_start:
print()
print('\nModels:')
print('num models = %s' % len(self.models))
for index, model in enumerate(self.models):
print('Model %d:' % index)
model.print_model(vis_env=True, aux_env=True,
compare=True, best_condition=True)
if new_line_end:
print()
def print_global_sets(self, indent=DEFAULT_INDENT, num_indents=0,
new_line_start=False, new_line_end=False,
draw_line=DEFAULT_DRAW_LINE):
if DEBUG_WITH_CONSOLE or DEBUG_WITH_LOGFILE:
pprint('Global Sets:', indent=indent, num_indents=num_indents,
new_line_start=new_line_start, draw_line=draw_line)
pprint('all visual values ever seen: \t%s' %
np.array(list(self.vis_global_set)).astype(int),
indent=indent, num_indents=num_indents + 1)
pprint('all focus values ever seen: \t%s' %
np.array(list(self.focus_global_set)).astype(int),
indent=indent, num_indents=num_indents + 1)
pprint('all auxiliary values ever seen:\t%s' %
np.array(list(self.aux_global_set)).astype(int),
indent=indent, num_indents=num_indents + 1,
new_line_end=new_line_end, draw_line=draw_line)
def print_goal_source(self, indent=DEFAULT_INDENT, num_indents=0,
new_line_start=False, new_line_end=False,
draw_line=DEFAULT_DRAW_LINE):
if DEBUG_WITH_CONSOLE or DEBUG_WITH_LOGFILE:
pprint('Goal Source:',
indent=indent, num_indents=num_indents,
new_line_start=new_line_start, draw_line=draw_line)
pprint('Source value:\t%s' % self.goal_source['value'],
indent=indent, num_indents=num_indents + 1)
pprint('x: \t%s' % self.goal_source['x'],
indent=indent, num_indents=num_indents + 1)
pprint('y: \t%s' % self.goal_source['y'],
indent=indent, num_indents=num_indents + 1)
pprint('i: \t%s' % self.goal_source['i'],
indent=indent, num_indents=num_indents + 1)
pprint('Goal value: \t%s' % self.goal_value,
indent=indent, num_indents=num_indents + 1,
new_line_end=new_line_end, draw_line=draw_line)
def print_change_lists(self, indent=DEFAULT_INDENT, num_indents=0,
new_line_start=False, new_line_end=False,
draw_line=DEFAULT_DRAW_LINE):
if DEBUG_WITH_CONSOLE or DEBUG_WITH_LOGFILE:
pprint('Visual Change List: \t\t%s' % self.vis_change_list,
indent=indent, num_indents=num_indents,
new_line_start=new_line_start, draw_line=draw_line)
pprint('Auxiliary Change List:\t\t%s' % self.aux_change_list,
indent=indent, num_indents=num_indents,
new_line_end=new_line_end, draw_line=draw_line)
def print_condition_id(self, indent=DEFAULT_INDENT, num_indents=0,
new_line_start=False, new_line_end=False,
draw_line=DEFAULT_DRAW_LINE):
if DEBUG_WITH_CONSOLE or DEBUG_WITH_LOGFILE:
pprint('Condition ID:\t\t%s' % self.condition_id,
indent=indent, num_indents=num_indents,
new_line_start=new_line_start, new_line_end=new_line_end,
draw_line=draw_line)
def print_knowledge(self, indent=DEFAULT_INDENT, num_indents=0,
new_line_start=False, new_line_end=False,
draw_line=DEFAULT_DRAW_LINE):
if DEBUG_WITH_CONSOLE or DEBUG_WITH_LOGFILE:
pprint('Knowledge:', indent=indent, num_indents=num_indents,
new_line_start=new_line_start, draw_line=draw_line)
pprint('size: %s' % sys.getsizeof(self.knowledge),
indent=indent, num_indents=num_indents + 1)
if self.knowledge:
pprint('Actions:', indent=indent, num_indents=num_indents + 1)
for action in self.knowledge['action set']:
action = str(action)
action_path = action
try:
action_outputs = self.knowledge[action_path]
pprint(action, indent=indent, num_indents=num_indents + 2)
pprint('Outputs:', indent=indent, num_indents=num_indents + 3)
for output in action_outputs:
output = str(output)
output_path = action_path + '/' + output
try:
condition_focus_values = self.knowledge[output_path]
pprint(output, indent=indent, num_indents=num_indents + 4)
pprint('Condition Focus Values:', indent=indent, num_indents=num_indents + 5)
for condition_focus_value in condition_focus_values:
condition_focus_value = str(condition_focus_value)
focus_path = output_path + '/' + condition_focus_value
try:
condition_ids = self.knowledge[focus_path]
pprint(condition_focus_value, indent=indent, num_indents=num_indents + 6)
pprint('Condition IDs:', indent=indent, num_indents=num_indents + 7)
for condition_id in condition_ids:
condition_id = str(condition_id)
id_path = focus_path + '/' + condition_id
try:
# path + '/posterior_val' is used b/c all conditions have one
id_exists = self.knowledge[id_path + '/posterior_val']
pprint(condition_id, indent=indent, num_indents=num_indents + 8)
except:
continue # don't search for knowledge of this condition_id if it doesnt exist
try:
pprint('rel_abs: %s' % self.knowledge[id_path + '/rel_abs'], indent=indent, num_indents=num_indents + 9)
except KeyError:
pass
try:
pprint('posterior_val: %s' % self.knowledge[id_path + '/posterior_val'], indent=indent, num_indents=num_indents + 9)
except KeyError:
pass
try:
x, y = self.knowledge[id_path + '/focus_x'], self.knowledge[id_path + '/focus_y']
pprint('(focus_x, focus_y): (%s, %s)' % (x, y), indent=indent, num_indents=num_indents + 9)
except KeyError:
pass
try:
pprint('focus_i: %s' % self.knowledge[id_path + '/focus_i'], indent=indent, num_indents=num_indents + 9)
except KeyError:
pass
try:
pprint('aux_ref: %s' % self.knowledge[id_path + '/aux_ref'], indent=indent, num_indents=num_indents + 9)
except KeyError:
pass
try:
pprint('aux_data: %s' % self.knowledge[id_path + '/aux_data'], indent=indent, num_indents=num_indents + 9)
except KeyError:
pass
try:
pprint('vis_ref: %s' % self.knowledge[id_path + '/vis_ref'], indent=indent, num_indents=num_indents + 9)
except KeyError:
pass
try:
print_vis_env(self.knowledge[id_path + '/vis_data'], title='vis_data', indent=indent, num_indents=num_indents + 9)
except KeyError:
pass
try:
pprint('post_aux_data: %s' % self.knowledge[id_path + '/post_aux_data'], indent=indent, num_indents=num_indents + 9)
except KeyError:
pass
try:
print_vis_env(self.knowledge[id_path + '/post_vis_data'], title='post_vis_data', indent=indent, num_indents=num_indents + 9)
except KeyError:
pass
except KeyError:
pass
except KeyError:
pass
except KeyError:
pass
else:
pprint('Empty', indent=indent, num_indents=num_indents + 1)
# bug: the line isn't drawn regardless, buts not a big deal
if new_line_end:
pprint('', indent=indent, num_indents=num_indents, draw_line=draw_line)
def print_knowledge_dictionary_raw(self, indent=DEFAULT_INDENT, num_indents=0,
new_line_start=False, new_line_end=False,
draw_line=DEFAULT_DRAW_LINE):
if DEBUG_WITH_CONSOLE or DEBUG_WITH_LOGFILE:
pprint('Knowledge:', indent=indent, num_indents=num_indents,
new_line_start=new_line_start, draw_line=draw_line)
if self.knowledge:
first = True
for k, v in self.knowledge.items():
if first:
first = False
pprint('key: %s' % k, indent=indent, num_indents=num_indents + 1)
else:
pprint('key: %s' % k, indent=indent,
num_indents=num_indents + 1, new_line_start=True, draw_line=False)
if isinstance(v, np.ndarray) and v.ndim == 2:
pprint('value:', indent=indent, num_indents=num_indents + 1)
print_vis_env(v, indent=indent, num_indents=num_indents + 1)
else:
pprint('value: %s' % v, indent=indent, num_indents=num_indents + 1)
else:
pprint('Empty', indent=indent, num_indents=num_indents + 1)
def print_focus_value(self, indent=DEFAULT_INDENT, num_indents=0,
new_line_start=False, new_line_end=False,
draw_line=DEFAULT_DRAW_LINE):
if DEBUG_WITH_CONSOLE or DEBUG_WITH_LOGFILE:
pprint('Focus Value:\t\t%s' % self.models[self.current_model_index].focus_value,
indent=indent, num_indents=num_indents,
new_line_start=new_line_start, new_line_end=new_line_end,
draw_line=draw_line)
def print_goal_condition(self, indent=DEFAULT_INDENT, num_indents=0,
new_line_start=False, new_line_end=False,
draw_line=DEFAULT_DRAW_LINE):
if DEBUG_WITH_CONSOLE or DEBUG_WITH_LOGFILE:
pprint('Goal Condition:\t\t%s' % self.goal_condition,
indent=indent, num_indents=num_indents,
new_line_start=new_line_start, new_line_end=new_line_end,
draw_line=draw_line)
def capture_input(self, vis_env, aux_env, action, prior=True, num_indents=0):
# main loop of AIRIS
pprint('capturing input ...', num_indents=num_indents,
new_line_start=True)
start_time = datetime.now()
# if the vis_env and aux_env being input is
# prior to the action being taken
if prior:
# save this environment
pprint('storing env before the action (prior) ...',
num_indents=num_indents + 1, new_line_start=True)
self.prior_vis_env = np.array(vis_env, dtype=np.float32)
self.prior_aux_env = np.array(aux_env, dtype=np.float32)
print_vis_env(self.prior_vis_env, title='self.prior_vis_env:', num_indents=num_indents + 2)
print_aux_env(self.prior_aux_env, title='self.prior_aux_env:', num_indents=num_indents + 2)
# if its not made a plan yet
while not self.action_plan:
pprint('no plan has been made yet',
num_indents=num_indents + 1, new_line_start=True)
pprint('self.action_plan:\t%s' % self.action_plan,
num_indents=num_indents + 2)
# clear old models, create a new model of this environment
# and set the current model index to that model
self.current_model_index = None
for i in self.models:
del i
self.current_model_index = self.create_model(-1, num_indents=num_indents + 2)
# why is this a while loop ................................
pprint('while there is no plan ...',
num_indents=num_indents + 2, new_line_start=True)
self.store_worst_index = None
self.store_worst = None
# not really sure what this does .......................
self.set_goal(self.goal_type, num_indents=num_indents + 3)
# make a plan to achieve the set goal
self.make_plan(action, num_indents=num_indents + 3)
self.display_hold = True
# get the action at the end of the list
if self.store_worst_index != None and len(self.action_plan) == 1:
pprint('Adding to worst set: '+str(self.store_worst),
num_indents=num_indents + 1, new_line_start=True)
self.worst_set.add(self.store_worst)
if self.goal_type == 'Observe':
print('Observed: ',self.action_plan)
self.display_plan = [0]
hold_plan = copy.deepcopy(self.action_plan)
while hold_plan:
self.display_plan.append(hold_plan.pop()[2])
pprint('popping the next action/output off the end of the plan ...',
num_indents=num_indents + 1, new_line_start=True)
action, output, predicted_model_index = self.action_plan.pop()
self.current_model_index = predicted_model_index
pprint('(action, output, predicted_model_index) = (%s, %s, %s)'
% (action, output, predicted_model_index),
num_indents=num_indents + 1)
pprint('do the action in the game', num_indents=1, new_line_start=True)
pprint('input captured. duration: %s' % (datetime.now() - start_time),
new_line_start=True, draw_line=True)
return (action, self.models[self.current_model_index].predicted_vis_change, self.models[self.current_model_index].predicted_aux_change)
# else, the vis_env and aux_env being input is posterior
# to the action that was taken
else:
# save this environment
pprint('storing env after the action (posterior) ...',
num_indents=num_indents + 1, new_line_start=True)
self.posterior_vis_env = np.array(vis_env, dtype=np.float32)
self.posterior_aux_env = np.array(aux_env, dtype=np.float32)
print_vis_env(self.posterior_vis_env, title='self.posterior_vis_env:', num_indents=num_indents + 2)
print_aux_env(self.posterior_aux_env, title='self.posterior_aux_env:', num_indents=num_indents + 2)
# determine if our prediction was correct
bad_prediction = self.find_changes(num_indents=num_indents + 1)
# if the condition was incorrect, update the knowledge
if bad_prediction or (self.goal_type == 'New Action' and not self.action_plan):
self.create_condition(action, '1', num_indents=num_indents + 1)
# self.print_mind(prior=False)
pprint('input captured. duration: %s' % (datetime.now() - start_time),
new_line_start=True, draw_line=True)
def create_model(self, from_model_index, num_indents=0):
# creates a model and puts it at the end of the self.models list
# for the 1st model
if from_model_index < 0:
pprint('creating a model from this environment ...',
num_indents=num_indents, new_line_start=True)
start_time = datetime.now()
# create the model
self.models = [Model(vis_env=self.prior_vis_env, aux_env=self.prior_aux_env)]
self.models[0].print_model(title='Model 0:', vis_env=True, aux_env=True,
vis_count_heap=True, compare=True, focus=True, best_condition=True, num_indents=num_indents + 1,
new_line_start=True)
# add any new inputs to the visual and non-visual global sets
pprint('adding any new inputs to the visual and auxiliary global sets',
num_indents=num_indents + 1, new_line_start=True)
self.vis_global_set.update(set(self.prior_vis_env.flatten()))
self.aux_global_set.update(set(self.prior_aux_env))
self.print_global_sets(num_indents=num_indents + 1)
focus_heap = copy.deepcopy(self.models[0].vis_count_heap)
if self.focus_global_set:
while focus_heap and self.models[0].focus_value == None:
if focus_heap[0][1] in self.focus_global_set:
self.models[0].focus_value = focus_heap[0][1]
else:
heapq.heappop(focus_heap)
if self.models[0].focus_value == None:
not_focus_heap = copy.deepcopy(self.models[0].vis_count_heap)
while not_focus_heap and self.models[0].focus_value == None:
if not_focus_heap[0][1] not in self.not_focus_global_set:
self.models[0].focus_value = not_focus_heap[0][1]
else:
heapq.heappop(not_focus_heap)
if self.models[0].focus_value == None:
self.models[0].focus_value = self.models[0].vis_count_heap[0][1]
else: # for the rest of the models
pprint('creating a model from model %s ...' % from_model_index,
num_indents=num_indents, new_line_start=True)
start_time = datetime.now()
# put a copy of the current model at the end of the list of models
self.models.append(
Model(prev_model=self.models[from_model_index],
prev_model_index=from_model_index))
pprint('updating self.current_model_index', num_indents=num_indents + 1,
new_line_start=True)
pprint('from:\t\t\t%s' % self.current_model_index, num_indents=num_indents + 2)
pprint('to: \t\t\t%s' % (len(self.models) - 1), num_indents=num_indents + 2)
pprint('model created. duration: %s' % (datetime.now() - start_time),
num_indents=num_indents, new_line_start=True, draw_line=True)
return len(self.models) - 1
def set_goal(self, goal_type, num_indents=0):
# picks a random condition from a random action
# grabs any other values that changed in that condition
# it finds a value in a random condition in its knowledge
# sets that value (or a value from its memory of all the values its ever seen)
# to its goal value
#
# what is a condition
# a condition is inside the knowledge it is any memory of an event happening
# capture of the state of the world prior to some event happening
self.goal_action = None
self.goal_output = None
self.goal_source = {
'value': None,
'x': None, # x of goal value relative to focus value
'y': None, # y of goal value relative to focus value
'i': None # i is for if the goal_source is an auxiliary input
}
self.goal_condition = None
self.goal_value = None
pprint('setting a goal ...',
num_indents=num_indents, new_line_start=True)
start_time = datetime.now()
goal_found = False
model = self.models[self.current_model_index]
no_conditions = False
# pick a random action
pprint('picking a random action/output ...', num_indents=num_indents + 1,
new_line_start=True)
action_index = random.choice(range(len(self.action_space)))
self.goal_action = self.action_space[action_index]
# pick a random output
# # right now self.goal_output is inevitably going to be 1
action_output = self.action_output_list[action_index]
output_range = range(action_output[0], action_output[1], action_output[2])
self.goal_output = str(random.choice(output_range))
pprint('self.goal_action = %s' % self.goal_action, num_indents=num_indents + 2)
pprint('self.goal_output = %s' % self.goal_output, num_indents=num_indents + 2)
pprint('goal_type: %s' % self.goal_type,
num_indents=num_indents + 1, new_line_start=True)
if self.goal_type == 'Random':
pprint('searching for knowledge of this action/output',
num_indents=num_indents + 1, new_line_start=True, draw_line=False)
# see if there's knowledge of this random action/output
try:
# knowledge_found will be the list of all the focus values
# for that action/output pair
path = str(self.goal_action) + '/' + str(self.goal_output)
knowledge_found = copy.deepcopy(self.knowledge[path])
knowledge_prune = []
pprint('knowledge found.', num_indents=num_indents + 2)
# set self.focus_pos to the pos of a focus_value in the current model
model = self.models[self.current_model_index] # current model
# prune all knowledge found whose focus_value is not in model.vis_env_count_list
pprint('Pruning found knowledge:', num_indents=num_indents + 2)
for knowledge_focus in knowledge_found:
if knowledge_focus[0] != 'A':
if float(knowledge_focus) not in model.vis_count_list:
pprint('focus value ' + str(knowledge_focus) + ' not in visual count', num_indents=num_indents + 3)
knowledge_prune.append(knowledge_focus)
for val in knowledge_prune:
knowledge_found.remove(val)
knowledge_prune = []
# prune all knowledge found whose focus value does not change and does not have /vis_ref
for knowledge_focus in knowledge_found:
keep = False
for check_condition in self.knowledge[path + '/' + str(knowledge_focus)]:
try:
found_vis_ref = self.knowledge[path + '/' + str(knowledge_focus) + '/' + str(check_condition) + '/vis_ref']
for x, y, prior_val, _ in found_vis_ref:
try:
if model.vis_count[prior_val]:
keep = True
break
except KeyError:
pass
except KeyError:
pass
if not keep:
pprint('focus value ' + str(knowledge_focus) + ' no vis_ref in any condition data', num_indents=num_indents + 3)
knowledge_prune.append(knowledge_focus)
for val in knowledge_prune:
if len(knowledge_found) > 1:
knowledge_found.remove(val)
else:
no_conditions = True
# set model.focus_value to a random focus value in knowledge_found
pprint('selecting a random focus_value from the usable knowledge:', num_indents=num_indents + 2)
if knowledge_found:
model.focus_value = random.choice(knowledge_found)
else:
raise KeyError
# flag if focus value is aux, set aux variable,
# and cast focus_value to float
model.focus_value_is_aux = model.focus_value[0] == 'A'
if not model.focus_value_is_aux:
# (x, y) position of a model.focus_value in the
# list of positions for that value in the model
model.focus_pos = model.vis_count_pos[float(model.focus_value)][0]
model.focus_value = float(model.focus_value[1:]) if \
model.focus_value_is_aux else float(model.focus_value)
self.goal_focus_value = copy.deepcopy(model.focus_value)
self.print_focus_value(num_indents=4)
pprint('flag model.focus_value_is_aux:\t%s' %
model.focus_value_is_aux, num_indents=num_indents + 2)
# choose a random goal condition
pprint('selecting a random goal_condition from the knowledge:',
num_indents=num_indents + 2, new_line_start=True)
#self.goal_condition = random.choice(
#self.knowledge[path + '/' + str(model.focus_value)])
if not no_conditions:
check_conditions = copy.deepcopy(self.knowledge[path + '/' + str(model.focus_value)])
self.goal_condition = random.choice(check_conditions)
while check_conditions:
try:
found_vis_ref = self.knowledge[path + '/' + str(model.focus_value) + '/' + str(self.goal_condition) + '/vis_ref']
found = False
for x, y, prior_val, _ in found_vis_ref:
try:
if model.vis_count[prior_val]:
found = True
break
except:
pass
if found:
break
else:
check_conditions.remove(self.goal_condition)
self.goal_condition = random.choice(check_conditions)
except KeyError:
check_conditions.remove(self.goal_condition)
self.goal_condition = random.choice(check_conditions)
if not check_conditions:
no_conditions = True
self.goal_condition = None
self.print_goal_condition(num_indents=4)
self.goal_type = self.goal_type_default
except KeyError:
pprint('we have no knowledge of this action/output', num_indents=num_indents + 2)
self.goal_type = 'New Action' # do an action we've not done before
goal_found = True
pprint('goal_type reset to:\t%s' % self.goal_type, num_indents=num_indents + 2)
if self.goal_type == 'Predict':
goal_found = True
if self.goal_type == 'Observe':
goal_found = True
fv = str(model.focus_value) if model.focus_value else ''
gc = str(self.goal_condition) if self.goal_condition else ''
path = str(self.goal_action) + '/' + str(self.goal_output) \
+ '/' + fv + '/' + gc
# fv and gc are used because: TypeError: must be str, not NoneType
# when using model.focus_value and self.goal_condition directly
if not goal_found and not no_conditions:
try:
pprint('searching for goal_source knowledge at: ' + path + '/vis_ref',
num_indents=num_indents + 1, new_line_start=True)
while True:
x, y, prior_val, _ = random.choice(self.knowledge[path + '/vis_ref'])
try:
if model.vis_count[prior_val]:
self.goal_source = {
'value': prior_val,
'x': x,
'y': y,
'i': None
}
self.goal_value = 3.0 #force airis to chase batteries
#self.goal_value = prior_val if goal_type == 'Fixed' else \
#random.sample(self.vis_global_set, 1)[0]
goal_found = True
pprint('knowledge found, goal_source set to:', num_indents=num_indents + 2)
self.print_goal_source(num_indents=num_indents + 3)
break
except KeyError:
pass
except KeyError:
pprint('knowledge not found', num_indents=num_indents + 2)
# pass
if not goal_found and not no_conditions:
try:
pprint('searching for goal_source knowledge at: ' + path + '/aux_ref',
num_indents=num_indents + 1, new_line_start=True)
i, val = random.choice(self.knowledge[path + '/aux_ref'])
self.goal_source = {
'value': val,
'x': None,
'y': None,
'i': i
}
self.goal_value = val if self.goal_type == 'Fixed' else \
random.sample(self.aux_global_set, 1)[0]
goal_found = True
pprint('knowledge found, goal_source set to:', num_indents=num_indents + 2)
self.print_goal_source(num_indents=num_indents + 3)
except KeyError:
pprint('knowledge not found', num_indents=num_indents + 2)
# pass
if not no_conditions:
pprint('goal set. duration: %s' % (datetime.now() - start_time),
num_indents=num_indents, new_line_start=True, draw_line=True)
def make_plan(self, action, num_indents=0):
# tbd when goal_type is not New Action
pprint('making a plan to achieve the goal ...',
num_indents=num_indents, new_line_start=True)
start_time = datetime.now()
pprint('goal_type: %s' % self.goal_type,
num_indents=num_indents + 1, new_line_start=True)
# how many steps are in the plan
plan_depth = 0
worst_condition = []
new_condition = []
if self.goal_type == 'Random' and self.goal_value != None:
# set the current model's compare field
self.compare_model(self.current_model_index, num_indents=num_indents + 1)
model = self.models[self.current_model_index] # get current model
model.depth = 0
# how far away that model is from the goal state, and its index
# use this heap to generate more models on as we go
base_model_heap = [(model.compare, self.current_model_index)]
# a way to see if a model has already been generated
# model_set = {model}
# make sure you don't generate the same sequence of models over and over again in an infinite loop
# if we modeled something and we model it again and it has the same result, then we discard that model
model_set = {np.array_str(model.vis_env) + np.array_str(model.aux_env)}
# flag if we've reached the goal
print('Current Goal: ')
print(self.goal_source,'where value =',self.goal_value)
goal_reached = False
print('Initial focus value', model.focus_value)
print('Initial Compare: ', model.compare)
if model.compare == 0:
self.predict(self.goal_action, self.goal_output, num_indents=num_indents + 1)
self.action_plan.append((self.goal_action, self.goal_output, self.current_model_index))
goal_reached = True
if model.compare == 999999:
goal_reached = True
while not goal_reached and base_model_heap and plan_depth <= self.action_plan_depth_limit:
base_model = heapq.heappop(base_model_heap)[1]
plan_depth += 1
pprint (str(plan_depth) + ' / ' + str(self.action_plan_depth_limit), num_indents=num_indents + 1)
for action_index, try_action in enumerate(self.action_space):
if not goal_reached:
for try_output in range(self.action_output_list[action_index][0], self.action_output_list[action_index][1], self.action_output_list[action_index][2]):
self.current_model_index = base_model
model = self.models[self.current_model_index]
hold_depth = model.depth
pprint('base model depth: '+str(model.depth), num_indents=num_indents + 1)
self.predict(try_action, try_output, num_indents=num_indents + 1)
if model.best_condition_id:
worst_dif = int(copy.deepcopy(model.best_condition_dif))
worst_id = int(copy.deepcopy(model.best_condition_id))
prev_model = model
model = self.models[self.current_model_index]
model.depth = hold_depth + 1
self.compare_model(self.current_model_index, num_indents=num_indents + 1)
if model.compare != 999999:
worst_condition.append((worst_dif, model.previous_model_index, worst_id, model.compare, try_action, try_output, 999999, prev_model.focus_value, self.current_model_index))
pprint('This model\'s (' + str(self.current_model_index) + ') depth: '+str(model.depth), num_indents=num_indents + 1)
pprint('This model\'s (' + str(self.current_model_index) + ') compare: '+str(model.compare), num_indents=num_indents + 1)
model_env = np.array_str(model.vis_env) \
+ np.array_str(model.aux_env)
if model_env not in model_set:
heapq.heappush(base_model_heap, (model.compare + model.depth, self.current_model_index))
model_set.add(model_env)
if model.compare == 0:
pprint('model compare Exception', num_indents=num_indents + 1)
self.predict(self.goal_action,self.goal_output, num_indents=num_indents + 1)
if model.best_condition_id:
source = self.current_model_index
model = self.models[source]
else:
source = self.models[self.current_model_index].previous_model_index
self.action_plan.append((self.goal_action, self.goal_output, source))
model = self.models[source]
while model.previous_model_index != None:
self.action_plan.append((model.previous_action, model.previous_output, source))
source = model.previous_model_index
model = self.models[source] # model.previous is an index
goal_reached = True
break
elif model.best_condition_id == None: # if we don't have knowledge of this try_action
source = self.models[self.current_model_index].previous_model_index
new_condition.append((999999, self.current_model_index, None, self.models[source].compare , try_action, try_output, 999999, self.models[source].focus_value, self.current_model_index))
else:
pprint('PLAN MADE!', num_indents=num_indents + 1)
break
# if no successful plan can be found, make a plan to try the least accurate prediction
if (plan_depth > self.action_plan_depth_limit or not self.action_plan) and not goal_reached:
if model.compare != 0:
print('Insufficient knowledge to achieve: ')
print(self.goal_source,'where value =',self.goal_value)
if plan_depth > self.action_plan_depth_limit:
self.action_plan_depth_limit += 5
print('Increasing plan depth to ',str(self.action_plan_depth_limit))
worst_condition.extend(new_condition)
for i, (dif, index, id, compare, act, out, raw, focus, current) in enumerate(worst_condition):
if id != None:
raw_dif = 0
path = str(act) + '/' + str(out) + '/' + str(focus) + '/' + str(id) + '/'
condition_data_array = self.knowledge[path + 'vis_data']
condition_aux_data_array = self.knowledge[path + 'aux_data']
raw_dif = np.sum(array_dif(self.models[index].vis_env, condition_data_array))
raw_dif += np.sum(array_dif(self.models[index].aux_env, condition_aux_data_array))
worst_condition[i] = (dif, index, id, compare, act, out, raw_dif, focus, current)
worst_condition_prune = copy.deepcopy(worst_condition)
worst_condition_check = copy.deepcopy(worst_condition)
for dif, index, id, compare, act, out, raw, focus, current in worst_condition_prune:
check_worst = (str(self.models[index].vis_env)+str(self.models[index].aux_env), act, out, raw)
if check_worst in self.worst_set:
pprint('deleting duplicate worst_condition: ('+str(dif)+','+str(index)+','+str(act)+','+str(out)+','+str(raw)+')', num_indents=num_indents + 1)
#print('deleting duplicate worst_condition: ('+str(dif)+','+str(index)+','+str(act)+','+str(out)+','+str(raw)+')')
worst_condition.remove((dif, index, id, compare, act, out, raw, focus, current))
worst_condition = [i for i in worst_condition if i[3] == min(worst_condition, key=itemgetter(3))[3]]
worst_condition_prune = [i for i in worst_condition if i[0] > 0]
if worst_condition_prune:
worst_condition = worst_condition_prune
worst_condition_prune = [i for i in worst_condition if i[6] != 0]
if worst_condition_prune:
worst_condition = worst_condition_prune
worst_condition = [i for i in worst_condition if i[6] == min(worst_condition, key=itemgetter(6))[6]]
# search through all models to find the one with the highest best_condition_dif
# if we cant figure out how to achieve our goal
# then instead, do whatever action we're the least confident about to see what action to do
if worst_condition:
pprint('worst_condition: '+str(worst_condition), num_indents=num_indents + 1)
print('Trying the closest thing I can think of...')
print('worst_condition: ', worst_condition)
worst_index = worst_condition.index(min(worst_condition, key=itemgetter(3)))
worst_index = worst_condition.index(max(worst_condition, key=itemgetter(0)))
self.store_worst = (str(self.models[worst_condition[worst_index][1]].vis_env)+str(self.models[worst_condition[worst_index][1]].aux_env), worst_condition[worst_index][4], worst_condition[worst_index][5], worst_condition[worst_index][6])
self.store_worst_index = worst_condition[worst_index][1]
self.current_model_index = worst_condition[worst_index][1]
if worst_condition[worst_index][0] == 0:
print('I think I\'ve tried \''+str(worst_condition[worst_index][4])+'\' under these conditions before.')
self.action_plan.append((worst_condition[worst_index][4], worst_condition[worst_index][5], worst_condition[worst_index][8]))
elif worst_condition[worst_index][0] == 999999:
pprint('New Action Exception', num_indents=num_indents + 1)
print('I don\'t know what will happen when I \''+str(worst_condition[worst_index][4])+'\' under these conditions...')
self.action_plan.append((worst_condition[worst_index][4], worst_condition[worst_index][5], worst_condition[worst_index][8]))
self.current_model_index = self.models[self.current_model_index].previous_model_index
elif 0 < worst_condition[worst_index][0] < 999999:
print('I\'m not sure about trying \''+str(worst_condition[worst_index][4])+'\' under these conditions...')
self.action_plan.append((worst_condition[worst_index][4], worst_condition[worst_index][5], worst_condition[worst_index][8]))
pprint('Cannot determine how to achieve goal.', num_indents=num_indents + 1)
pprint('Attempting worst_condition: '+str(worst_condition[worst_index]), num_indents=num_indents + 1)
if self.current_model_index != None:
model = self.models[self.current_model_index]
while model.previous_model_index != None:
self.action_plan.append((model.previous_action, model.previous_output, self.current_model_index))
self.current_model_index = model.previous_model_index
model = self.models[self.current_model_index]
print('Action plan: ',self.action_plan)
else:
pprint('Cannot determine how to achieve goal.', num_indents=num_indents + 1)
pprint('No more worst_condition\'s left to try.', num_indents=num_indents + 1)
#pprint('Clearing worst_set:', num_indents=num_indents)
#self.worst_set.clear()
#print('Clearing worst_set')
pprint('Abandoning goal.', num_indents=num_indents + 1)
print('No more worst_conditions? Check ',worst_condition_check)
elif self.goal_type == 'New Action':
pprint('since the goal type is New Action', num_indents=num_indents + 2)
pprint('just append the randomly determined action/output', num_indents=num_indents + 2)
pprint('to the plan, along with self.current_model_index', num_indents=num_indents + 2)
self.action_plan.append((self.goal_action, self.goal_output, 0))
elif self.goal_type == 'Predict':
pprint ('Making a prediction...', num_indents=num_indents + 1)
for action_index, try_action in enumerate(self.action_space):
for try_output in range(self.action_output_list[action_index][0], self.action_output_list[action_index][1], self.action_output_list[action_index][2]):
self.predict(try_action, try_output, num_indents=num_indents + 1)
self.action_plan.append((try_action, try_output, self.current_model_index))
pprint ('Plan: '+str(self.action_plan), num_indents=num_indents + 1)
elif self.goal_type == 'Observe':
pprint ('Observing...', num_indents=num_indents + 1)
self.predict(action, 1, num_indents=num_indents + 1)
self.action_plan.append((action, 1, self.current_model_index))
pprint ('Observed action: '+str(self.action_plan), num_indents=num_indents + 1)
pprint('self.action_plan:\t%s' % self.action_plan,
num_indents=num_indents + 1, new_line_start=True)
pprint('plan made. duration: %s' % (datetime.now() - start_time),
num_indents=num_indents, new_line_start=True, draw_line=True)
def compare_model(self, model_index, num_indents=0):
# set the specified model's compare field to the distance
# from the predicted goal value's pos to the closest actual goal value
pprint('compare_model: setting the specified model\'s compare field',
num_indents=num_indents, new_line_start=True, draw_line=False)
pprint('to the distance from the predicted goal value\'s pos to the',
num_indents=num_indents)