-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathComms_framework.py
2314 lines (1827 loc) · 123 KB
/
Comms_framework.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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#Import needed packages
import tensorflow as tf
import numpy as np
import design_specialist
import comms_problem
from tf_agents.environments import py_environment
from tf_agents.environments import tf_environment
from tf_agents.environments import tf_py_environment
from tf_agents.environments import utils
from tf_agents.specs import array_spec
from tf_agents.environments import wrappers
from tf_agents.environments import suite_gym
from tf_agents.trajectories import time_step as ts
import random
import gym
import copy
import math
#GOOD RESOURCE: https://github.com/tensorflow/agents/issues/27
#TODO: on refactor - find out a way to handle 'lower is better/higher is better'
#properties receiving target constraints (or at least lower AND upper bounded constraints) (make EVERYTHING use bounds?)
#TODO: Initialize histories with initial design as well, so we don't try to merge with an empty history (that makes... issues)
#TODO: EXTREMELY fancy move - use shared references to link goals and needs together, so that as one changes the goals can update and adapt.
#There might be some use to it, some day.
class comms_framework(gym.Env):
def __init__(self,params,problem = 'SAE'):
super(comms_framework,self).__init__()
#initial setup of framework
self.num_comms_actions = 0;
self.update_interval = params['update_interval'];
self.max_designs = params['max_designs'];
self.current_max_designs = self.max_designs;
self.max_compiler_iterations = params['compiler_iterations'];
self.compiler_starting_samples = params['compiler_starting_samples'];
self.spec_compiler_interval = params['compiler_interval'];
self.max_iterations = params['max_iterations'];
self.meeting_length = params['meeting_length']
self.reward_scale = params['reward_scale'];
self.target_tol = 0.05
#pareto optimization terms
self.dominance_coef = 30
self.proximity_coef = 2
self.proximity_eps = 0.5
self.proximity_coef_lin = 2
self.proximity_coef_target = 2
self.goal_penalty = 500
self.goal_scale = 1.5
#self.goal_threshold = 30
self.constraint_penalty = 1e6
self.incompatibility_penalty = 1e6
self.incompatibility_scale = 1e4
self.PENALTY_SCORE = 1e20
self.activity_penalty = 1
self.failed_comms_penalty = 10
self.integration_mode = 0
#read in problem
if problem == 'SAE':
self.problem = comms_problem.sae_problem()
elif problem == 'Convex':
self.problem = comms_problem.convex_problem(num_agents)
elif problem == 'S-P':
self.problem = comms_problem.sine_parabola_problem()
elif problem == 'variable_coord':
num_agents = params['VC_agents']
self.problem = comms_problem.variable_coord_problem(num_agents)
#self.problem = sae_problem()
self.num_agents = self.problem.number_of_agents
learn_rates = self.problem.learn_rates
actions_per_agent = self.problem.actions_per_agent + self.num_comms_actions
self.temps = self.problem.temps
self.pareto_weights = self.problem.pareto_weights
self.target_weights = self.problem.target_weights
if "learn_rate" in params:
learn_rates = np.ones_like(learn_rates)*params["learn_rate"]
self.timestep = 0;
#initialize design properties
self.active_agents = np.ones(self.num_agents) #set based init
#self.active_agents = np.zeros(self.num_agents) #point based init
self.committed = ([[copy.deepcopy(self.problem.subproblems[i])] for i in range(self.num_agents)]) #pack in an extra list for appending new problems
self.wip = copy.deepcopy(self.problem.subproblems)
for i in range(self.num_agents):
for j in range(self.max_designs-1): #Keeping it as this format because we might make max designs vary per designer
self.committed[i].append(copy.deepcopy(self.problem.subproblems[i]))
self.active_designs = ([np.zeros(self.max_designs) for i in range(self.num_agents)])
self.design_props = ([np.tile(self.problem.design_props[i],(self.max_designs,1)) for i in range(self.num_agents)])
self.design_targets = ([np.tile(self.problem.design_targets[i],(self.max_designs,1)) for i in range(self.num_agents)])
for i in range(self.num_agents):
self.active_designs[i][0] = 1
self.design_props[i][1:] = np.zeros_like(self.design_props[i][1:])
self.design_targets[i][1:] = np.zeros_like(self.design_targets[i][1:])
self.wip_props = copy.deepcopy(self.problem.design_props)
self.wip_targets = copy.deepcopy(self.problem.design_targets)
self.is_requested = np.zeros(self.num_agents)
self.design_needs = ([[copy.deepcopy(self.problem.subproblem_needs[i])] for i in range(self.num_agents)])
self.design_goals = ([[copy.deepcopy(self.problem.subproblem_goals[i])] for i in range(self.num_agents)])
self.target_needs = ([[copy.deepcopy(self.problem.target_needs[i])] for i in range(self.num_agents)])
self.target_goals = ([[copy.deepcopy(self.problem.target_goals[i])] for i in range(self.num_agents)])
#indexes for wip needs/goals: acting agent, needed agent's design, property of needed agent's design
self.wip_needs = copy.deepcopy(self.problem.subproblem_needs)
self.wip_goals = copy.deepcopy(self.problem.subproblem_goals)
self.wip_target_needs = copy.deepcopy(self.problem.target_needs)
self.wip_target_goals = copy.deepcopy(self.problem.target_goals)
for i in range(self.num_agents):
for j in range(self.max_designs-1):
#indexes for needs/goals: acting agent, acting design, needed agent's design, property of needed agent's design
self.design_needs[i].append(copy.deepcopy(self.problem.subproblem_needs[i]))
self.design_goals[i].append(copy.deepcopy(self.problem.subproblem_goals[i]))
self.target_needs[i].append(copy.deepcopy(self.problem.target_needs[i]))
self.target_goals[i].append(copy.deepcopy(self.problem.target_goals[i]))
self.previous_solutions = ([np.zeros(self.num_agents).astype(int) for i in range(self.num_agents)])
self.old_obj_funcs = np.asarray([self.local_objective(i,wip_props = self.wip_props[i],wip_targets = self.design_targets[i],wip_needs=[],wip_target_needs=[]) + self.check_constraints(i,self.wip[i]) for i in range(self.num_agents)])
#best solution saving
self.best_solution = np.zeros(self.num_agents).astype(int)
self.best_designs = ([copy.deepcopy(self.committed[i][0]) for i in range(self.num_agents)])
self.best_props = ([copy.deepcopy(self.design_props[i][0]) for i in range(self.num_agents)])
self.best_needs = ([copy.deepcopy(self.design_needs[i][0]) for i in range(self.num_agents)])
self.best_targets = ([copy.deepcopy(self.design_targets[i][0]) for i in range(self.num_agents)])
self.best_target_needs = ([copy.deepcopy(self.target_needs[i][0]) for i in range(self.num_agents)])
solution_props,solution_needs,solution_targets,solution_target_needs = self.get_solution_properties(self.best_solution)
self.best_solution_value = self.evaluate_solution(solution_props,solution_needs,solution_targets,solution_target_needs)
if self.best_solution_value >= self.PENALTY_SCORE:
self.best_solution_validity = 0
else:
self.best_solution_validity = 1
self.update_intervals = np.ones(self.num_agents)*self.update_interval
self.meeting_with = ([[] for i in range(self.num_agents)])
self.moved = np.zeros(self.num_agents)
self.meeting_timer = np.zeros(self.num_agents)
self.is_communicating = np.zeros(self.num_agents)
#initialize agents
self.team = ([design_specialist.design_specialist(actions_per_agent[i],learn_rates[i],self.temps[i],self.max_designs) for i in range(self.num_agents)])
#self.team = ([design_specialist(actions_per_agent[i],learn_rates[i],self.temps[i],self.max_designs) for i in range(self.num_agents)])
#precompute active need indices for referencing during observation construction
self.active_needs = []
self.ATN_lower = []
self.ATN_upper = []
for i in range(self.num_agents):
self.active_needs.append([])
self.ATN_lower.append([])
self.ATN_upper.append([])
for j in range(self.num_agents):
if i != j:
if len(self.design_needs[i][0][j]) == 0:
self.active_needs[i].append([])
else:
self.active_needs[i].append(np.nonzero(1-self.design_needs[i][0][j].mask)[0])
if len(self.target_needs[i][0][j]) == 0:
self.ATN_lower[i].append([])
self.ATN_upper[i].append([])
else:
idx1 = np.nonzero(1-self.target_needs[i][0][j].mask)[0]
idx2 = np.nonzero(1-self.target_needs[i][0][j].mask)[1]
self.ATN_lower[i].append([])
self.ATN_upper[i].append([])
for k in range(len(idx2)):
if idx2[k] == 0:
self.ATN_lower[i][j].append(idx1[k])
else:
self.ATN_upper[i][j].append(idx1[k])
else:
self.active_needs[i].append([])
self.ATN_lower[i].append([])
self.ATN_upper[i].append([])
#initialize action and observation spaces
highs = np.ones(9+self.num_agents)*1e4
#highs[9] = self.num_agents - 1e-2
#highs[10+3*self.num_agents] = self.num_agents - 1e-2
lows = -highs
#lows = np.zeros(9+self.num_agents)
#lows[0:9] = -1e6
#lows[9:9+self.num_agents] = -1
self.action_space = gym.spaces.Box(lows,highs,dtype=np.float16)
num_props = 0
num_needs = 0
for i in range(self.num_agents):
num_props += len(self.wip_props[i])
num_props += len(self.wip_targets[i])
for j in range(self.num_agents):
if i != j:
if len(self.wip_needs[i][j]) != 0:
num_needs += np.sum(1-self.wip_needs[i][j].mask)
if len(self.wip_target_needs[i][j]) != 0:
num_needs += np.sum(1-self.wip_target_needs[i][j].mask)
#communicating and active agents design props/needs active designs best value + time to deadline + best value being invalid
high = np.ones(self.num_agents*2+(num_props+num_needs+self.num_agents)*self.max_designs+4)*np.finfo(np.float32).max
self.observation_space = gym.spaces.Box(-high,high,dtype=np.float16) #States include capabilities of all subdesigns and the global objective function
def reset(self):
self.problem = comms_problem.sae_problem()
self.current_max_designs = self.max_designs;
self.integration_mode = 0
self.num_agents = self.problem.number_of_agents
learn_rates = self.problem.learn_rates
actions_per_agent = self.problem.actions_per_agent + self.num_comms_actions
self.temps = self.problem.temps
self.pareto_weights = self.problem.pareto_weights
self.target_weights = self.problem.target_weights
self.timestep = 0;
#initialize design properties
self.active_agents = np.ones(self.num_agents) #set based init
#self.active_agents = np.zeros(self.num_agents) #point based init
self.committed = ([[copy.deepcopy(self.problem.subproblems[i])] for i in range(self.num_agents)]) #pack in an extra list for appending new problems
self.wip = copy.deepcopy(self.problem.subproblems)
for i in range(self.num_agents):
for j in range(self.max_designs-1): #Keeping it as this format because we might make max designs vary per designer
self.committed[i].append(copy.deepcopy(self.problem.subproblems[i]))
self.active_designs = ([np.zeros(self.max_designs) for i in range(self.num_agents)])
self.design_props = ([np.tile(self.problem.design_props[i],(self.max_designs,1)) for i in range(self.num_agents)])
self.design_targets = ([np.tile(self.problem.design_targets[i],(self.max_designs,1)) for i in range(self.num_agents)])
for i in range(self.num_agents):
self.active_designs[i][0] = 1
self.design_props[i][1:] = np.zeros_like(self.design_props[i][1:])
self.design_targets[i][1:] = np.zeros_like(self.design_targets[i][1:])
self.wip_props = copy.deepcopy(self.problem.design_props)
self.wip_targets = copy.deepcopy(self.problem.design_targets)
self.is_requested = np.zeros(self.num_agents)
self.design_needs = ([[copy.deepcopy(self.problem.subproblem_needs[i])] for i in range(self.num_agents)])
self.design_goals = ([[copy.deepcopy(self.problem.subproblem_goals[i])] for i in range(self.num_agents)])
self.target_needs = ([[copy.deepcopy(self.problem.target_needs[i])] for i in range(self.num_agents)])
self.target_goals = ([[copy.deepcopy(self.problem.target_goals[i])] for i in range(self.num_agents)])
#indexes for wip needs/goals: acting agent, needed agent's design, property of needed agent's design
self.wip_needs = copy.deepcopy(self.problem.subproblem_needs)
self.wip_goals = copy.deepcopy(self.problem.subproblem_goals)
self.wip_target_needs = copy.deepcopy(self.problem.target_needs)
self.wip_target_goals = copy.deepcopy(self.problem.target_goals)
for i in range(self.num_agents):
for j in range(self.max_designs-1):
#indexes for needs/goals: acting agent, acting design, needed agent's design, property of needed agent's design
self.design_needs[i].append(copy.deepcopy(self.problem.subproblem_needs[i]))
self.design_goals[i].append(copy.deepcopy(self.problem.subproblem_goals[i]))
self.target_needs[i].append(copy.deepcopy(self.problem.target_needs[i]))
self.target_goals[i].append(copy.deepcopy(self.problem.target_goals[i]))
self.previous_solutions = ([np.zeros(self.num_agents).astype(int) for i in range(self.num_agents)])
self.old_obj_funcs = np.asarray([self.local_objective(i,wip_props = self.wip_props[i],wip_targets = self.design_targets[i],wip_needs=[],wip_target_needs=[]) + self.check_constraints(i,self.wip[i]) for i in range(self.num_agents)])
#best solution saving
self.best_solution = np.zeros(self.num_agents).astype(int)
self.best_designs = ([copy.deepcopy(self.committed[i][0]) for i in range(self.num_agents)])
self.best_props = ([copy.deepcopy(self.design_props[i][0]) for i in range(self.num_agents)])
self.best_needs = ([copy.deepcopy(self.design_needs[i][0]) for i in range(self.num_agents)])
self.best_targets = ([copy.deepcopy(self.design_targets[i][0]) for i in range(self.num_agents)])
self.best_target_needs = ([copy.deepcopy(self.target_needs[i][0]) for i in range(self.num_agents)])
solution_props,solution_needs,solution_targets,solution_target_needs = self.get_solution_properties(self.best_solution)
self.best_solution_value = self.evaluate_solution(solution_props,solution_needs,solution_targets,solution_target_needs)
if self.best_solution_value >= self.PENALTY_SCORE:
self.best_solution_validity = 0
else:
self.best_solution_validity = 1
self.update_intervals = np.ones(self.num_agents)*self.update_interval
self.meeting_with = ([[] for i in range(self.num_agents)])
self.moved = np.zeros(self.num_agents)
self.meeting_timer = np.zeros(self.num_agents)
self.is_communicating = np.zeros(self.num_agents)
#initialize agents
self.team = ([design_specialist.design_specialist(actions_per_agent[i],learn_rates[i],self.temps[i],self.max_designs) for i in range(self.num_agents)])
return self._next_observation()
def _next_observation(self):
#serialize all the designs and their needs
obs = np.asarray([])
for i in range(self.num_agents):
obs = np.concatenate([obs,self.active_designs[i]])
for j in range(self.max_designs):
needs = []
for k in range(self.num_agents):
for l in self.active_needs[i][k]:
needs.append(self.design_needs[i][j][k][l])
for l in self.ATN_lower[i][k]:
needs.append(self.target_needs[i][j][k][l,0])
for l in self.ATN_upper[i][k]:
needs.append(self.target_needs[i][j][k][l,1])
design_info = np.concatenate(([self.design_props[i][j],self.design_targets[i][j],needs]))
obs = np.concatenate([obs,design_info])
obs = np.concatenate([obs,
self.is_communicating,
self.active_agents,
[self.best_solution_value*self.reward_scale],
[self.max_iterations-self.timestep],
[self.integration_mode],
[self.best_solution_validity]])
return obs
def step(self, action_in):
#"""Apply action and return new time_step."""
#also return the new situation
#action = copy.deepcopy(action_in)
#action.flags.writeable=True
action = [np.argmax(action_in[0:9])]
agent_choices = copy.deepcopy(action_in[9:9+self.num_agents])
agent_choices.flags.writeable=True
#Figure out the action parser later once we're working on our RL agent.
#action #0 = 'do nothing'
old_best_solution = copy.deepcopy(self.best_solution_value)
success = 1
self.state_dict = {}
if action[0] < 2 and action[0] >= 1: #shrink design space
self.shrink_design_space()
elif action[0] < 3 and action[0] >= 2: #force an update of an agent's design
#agent = int(np.floor(action[1]))
agent = np.argmax(agent_choices)
success = self.merge_design(agent)
if success != None:
self.new_design(agent)
elif action[0] < 4 and action[0] >= 3: #make a request to have many agents fulfill one
#a1 = np.argmax(action[2:2+self.num_agents])
a1 = np.argmax(agent_choices)
agent_choices[a1] = 1e9
#a2 = np.nonzero(np.where(action[2:2+self.num_agents]<-0.9,1,0))[0]
a2 = np.nonzero(np.where(agent_choices < 0, 1, 0))[0]
if a2.size == 0:
#a2 = [np.argmin(action[2:2+self.num_agents])]
a2 = [np.argmin(agent_choices)]
if a1 == a2:
success = None
else:
success = self.demanding_request(a1,a2)
else:
success = self.demanding_request(a1,a2)
elif action[0] < 5 and action[0] >= 4: #make a request for one agent to fulfill many
a1 = np.argmax(agent_choices)
agent_choices[a1] = 1e9
a2 = np.nonzero(np.where(agent_choices < 0, 1, 0))[0]
if a2.size == 0:
a2 = [np.argmin(agent_choices)]
if a1 == a2:
success = None
else:
success = self.fulfilling_request(a1,a2)
else:
success = self.fulfilling_request(a1,a2)
elif action[0] < 6 and action[0] >= 5: #make a meeting
#meeting_agents = np.nonzero(np.where(action[2+2*self.num_agents:2+3*self.num_agents]>0.9,1,0))[0]
meeting_agents = np.nonzero(np.where(agent_choices>0,1,0))[0]
success = self.create_meeting(meeting_agents)
elif action[0] < 7 and action[0] >= 6: #start or stop an agent
#agent = int(np.floor(action[2+3*self.num_agents]))
agent = np.argmax(agent_choices)
self.start_stop(agent)
elif action[0] < 8 and action[0] >= 7:
self.expand_design_space()
elif action[0] < 9 and action[0] >= 8:
self.return_to_exploration()
self.state_dict["good_actions"] = np.zeros(self.num_agents)
self.state_dict["meeting_obj_func"] = self.best_solution_value
self.state_dict["replaced_designs"] = np.ones(self.num_agents)*-1
self.state_dict["forked_designs"] = np.zeros(self.num_agents)
self.state_dict["attempted_actions"] = np.zeros(self.num_agents)
self.state_dict["merged"] = 0
self.moved = np.zeros(self.num_agents)
for i in range(self.num_agents):
if self.active_agents[i] > 0.5:
if self.meeting_with[i] == []:
self.iterate_agent(i)
else:
self.iterate_meeting(i)
self.timestep += 1
obs = self._next_observation()
done = self.timestep == self.max_iterations
reward = -(self.best_solution_value - old_best_solution) - np.sum(self.active_agents)*self.activity_penalty
if success == None:
reward = reward - self.failed_comms_penalty
if reward > self.PENALTY_SCORE/10:
reward = 0
#TODO: Map the subproblems into cleanly viewable variables for the manager, no redundant information!
return obs,reward*self.reward_scale,done, {}
def render(self):
self.state_dict["active_designs"] = self.active_designs
self.state_dict["published_independent_vars"] = self.committed
self.state_dict["WIP_independent_vars"] = self.wip
self.state_dict["Published_dep_vars"] = self.design_props
self.state_dict["Published_dep_targets"] = self.design_targets
self.state_dict["Published_needs"] = self.design_needs
self.state_dict["Published_goals"] = self.design_goals
self.state_dict["Published_target_needs"] = self.target_needs
self.state_dict["Published_target_goals"] = self.target_goals
self.state_dict["wip_dep_vars"] = self.wip_props
self.state_dict["wip_dep_targets"] = self.wip_targets
self.state_dict["wip_needs"] = self.wip_needs
self.state_dict["wip_goals"] = self.wip_goals
self.state_dict["wip_target_needs"] = self.wip_target_needs
self.state_dict["wip_target_goals"] = self.wip_target_goals
self.state_dict["wip_solutions"] = self.previous_solutions
self.state_dict["old_obj_funcs"] = self.old_obj_funcs
self.state_dict["agents"] = self.team
return self.timestep,self.best_solution_value,self.integration_mode,self.active_agents,self.state_dict
def iterate_agent(self,agent_id):
if self.moved[agent_id] == 1:
raise Exception('agent in meeting is iterating individually!')
if self.timestep % self.update_intervals[agent_id] == 0 and self.is_requested[agent_id] == 0:
merged_idx = self.merge_design(agent_id)
self.new_design(agent_id)
self.state_dict["merged"] = 1
#Iterates on the problem
#Agent iterates on the problem, using others' committed subproblems, and its own wip subproblems
move_id = self.team[agent_id].select_move()
old_props,old_targets = self.problem.get_props(agent_id,self.wip[agent_id])
old_obj_func = self.old_obj_funcs[agent_id]
new_vars, new_needs, new_target_needs = self.problem.apply_move(agent_id,move_id,self.wip[agent_id], self.wip_needs[agent_id],self.wip_target_needs[agent_id]); #Check this later
new_props,new_targets = self.problem.get_props(agent_id,new_vars)
used_solution = self.previous_solutions[agent_id]
if self.integration_mode == 1:
penalty = self.check_constraints(agent_id,new_vars)
if penalty > 0:
new_obj_func = penalty
else:
props,needs,targets,target_needs = self.get_solution_properties(used_solution,[agent_id],new_props,new_needs,new_targets,new_target_needs)
goal_penalties = self.check_goals(agent_id,new_props,new_needs,self.wip_goals[agent_id])+self.check_targets(agent_id,new_targets,new_target_needs,self.wip_target_goals[agent_id])
if props != -1:
#evaluate how the design performs with the last solution used as well; useful for stability
new_obj_func = self.evaluate_solution(props,needs,targets,target_needs) + goal_penalties
else:
new_obj_func = self.PENALTY_SCORE
#periodically search for a new solution, or if the current one became invalid
if self.timestep % self.spec_compiler_interval == 0 or new_obj_func == self.PENALTY_SCORE:
new_obj_ns, new_solution = self.design_compiler([agent_id],new_props,new_needs,new_targets,new_target_needs)
new_obj_ns += goal_penalties
if new_obj_ns < new_obj_func:
new_obj_func = new_obj_ns
used_solution = new_solution
self.team[agent_id].active_hist_solution.append(used_solution)
else:
new_obj_func = self.local_objective(agent_id,new_props,new_needs,new_targets,new_target_needs) + self.check_constraints(agent_id,new_vars)
accept = self.team[agent_id].update_learn(new_obj_func - old_obj_func)
self.state_dict["good_actions"][agent_id] = int(new_obj_func < old_obj_func)
self.state_dict["attempted_actions"][agent_id] = move_id
#update history for future temperature updates
self.team[agent_id].active_hist.append(new_obj_func)
self.team[agent_id].active_hist_needs.append(new_needs)
self.team[agent_id].active_hist_target_needs.append(new_target_needs)
self.team[agent_id].active_hist_design.append(new_vars)
if (len(self.team[agent_id].active_hist) > self.team[agent_id].hist_length):
self.team[agent_id].active_hist.pop(0)
self.team[agent_id].active_hist_needs.pop(0)
self.team[agent_id].active_hist_target_needs.pop(0)
self.team[agent_id].active_hist_design.pop(0)
if self.integration_mode == 1:
self.team[agent_id].active_hist_solution.pop(0)
self.team[agent_id].update_temp()
if (accept == 1):
self.wip[agent_id] = new_vars
self.wip_needs[agent_id] = new_needs
self.wip_target_needs[agent_id] = new_target_needs
self.team[agent_id].move = move_id
self.wip_props[agent_id] = new_props
self.wip_targets[agent_id] = new_targets
self.old_obj_funcs[agent_id] = new_obj_func
self.previous_solutions[agent_id] = used_solution
if((self.is_requested[agent_id] == 1 and self.check_goals(agent_id,new_props,self.wip_needs[agent_id],self.wip_goals[agent_id]) <= 0) or self.meeting_timer[agent_id] >= self.meeting_length):
self.close_request(agent_id)
self.new_design(agent_id)
return
def shrink_design_space(self):
self.state_dict["culled_designs"] = np.zeros(self.num_agents)
if self.integration_mode == 0:
for i in range(self.num_agents):
self.team[i].reset_temps()
self.team[i].reset_histories()
#We also wipe all saved goals in integration mode;
#preserving integrative capability is done by global objective now
for j in range(self.max_designs):
self.design_goals[i][j] = copy.deepcopy(self.problem.needs_bases)
self.target_goals[i][j] = copy.deepcopy(self.problem.target_need_bases)
self.integration_mode = 1 #'throw the switch' and begin integrating
temp_max_designs = int(self.current_max_designs-1)
if temp_max_designs == 0:
temp_max_designs = 1
worst_objs = np.zeros(self.num_agents)
design_culled = 0
for i in range(self.num_agents): #cull down to the new max if needed
while np.sum(self.active_designs[i]) > temp_max_designs:
max_idx, max_obj = self.cull_design(i)
design_culled = 1
if design_culled == 1:
worst_objs[i] = max_obj
if design_culled == 1:
designs_removed = 1
while (designs_removed > 0 ):
designs_removed = 0
for i in range(self.num_agents):
designs_removed += self.remove_killed_designs(i,worst_objs[i])
self.current_max_designs = temp_max_designs
#also update wip designs with the new design space
for i in range(self.num_agents):
obj, solution = self.design_compiler([i],self.wip_props[i],self.wip_needs[i],self.wip_targets[i],self.wip_target_needs[i])
self.old_obj_funcs[i] = obj + self.check_constraints(i,self.wip[i])
self.previous_solutions[i] = solution
def switch_to_integration(self):
if self.integration_mode == 0:
for i in range(self.num_agents):
self.team[i].reset_temps()
self.team[i].reset_histories()
#We also wipe all saved goals in integration mode;
#preserving integrative capability is done by global objective now
for j in range(self.max_designs):
self.design_goals[i][j] = copy.deepcopy(self.problem.needs_bases)
self.target_goals[i][j] = copy.deepcopy(self.problem.target_need_bases)
self.integration_mode = 1 #'throw the switch' and begin integrating
#also update wip designs with the new design space
for i in range(self.num_agents):
obj, solution = self.design_compiler([i],self.wip_props[i],self.wip_needs[i],self.wip_targets[i],self.wip_target_needs[i])
self.old_obj_funcs[i] = obj + self.check_constraints(i,self.wip[i])
self.previous_solutions[i] = solution
def expand_design_space(self):
self.current_max_designs = math.ceil(self.current_max_designs*1.2)
if self.current_max_designs >= self.max_designs:
self.current_max_designs = self.max_designs
def return_to_exploration(self):
if self.integration_mode == 1:
for i in range(self.num_agents):
self.team[i].reset_temps()
self.team[i].reset_histories()
self.integration_mode = 0
self.current_max_designs = self.max_designs
for i in range(self.num_agents):
obj = self.local_objective(i,self.wip_props[i],self.wip_needs[i],self.wip_targets[i],self.wip_target_needs[i])+self.check_constraints(i,self.wip[i])
self.old_obj_funcs[i] = obj
def create_meeting(self,agent_ids):
if len(agent_ids) <= 1:
return
for i in agent_ids: #make sure no ones already communicating
if self.is_communicating[i]:
return
for i in agent_ids:
#set statuses to show agents as in a meeting
self.is_communicating[i] = 1
self.meeting_with[i] = agent_ids
merged_idx = self.merge_design(i)
obj,solution = self.design_compiler()
if type(solution) is int:
return
for i in agent_ids:
self.fork_design(i,solution[i])
#reset objective functions & histories
self.old_obj_funcs[i] = obj
self.previous_solutions[i] = solution
self.team[i].reset_active_histories()
self.team[i].reset_active_temps()
return 1
def iterate_meeting(self,agent_id):
if self.moved[agent_id] == 1:
return
agent_ids = self.meeting_with[agent_id]
#Iterates on the problem
#Agent iterates on the problem, using others' committed subproblems, and its own wip subproblems
meeting_size = len(agent_ids)
old_props = ([[] for i in range(meeting_size)])
old_targets = ([[] for i in range(meeting_size)])
old_obj_func = ([[] for i in range(meeting_size)])
move_id = ([[] for i in range(meeting_size)])
new_vars = ([[] for i in range(meeting_size)])
new_props = ([[] for i in range(meeting_size)])
new_targets = ([[] for i in range(meeting_size)])
new_needs = ([[] for i in range(meeting_size)])
new_target_needs = ([[] for i in range(meeting_size)])
old_obj_func = self.old_obj_funcs[agent_ids[0]]
self.state_dict["meeting_obj_func"] = old_obj_func
for i in range(meeting_size):
agent_id = agent_ids[i]
self.meeting_timer[agent_id] = self.meeting_timer[agent_id] + 1
move_id[i] = self.team[agent_id].select_move()
old_props[i],old_targets[i] = self.problem.get_props(agent_id,self.wip[agent_id])
new_vars[i], new_needs[i], new_target_needs[i] = self.problem.apply_move(agent_id,move_id[i],self.wip[agent_id],self.wip_needs[agent_id],self.wip_target_needs[agent_id]); #Check this later
new_props[i],new_targets[i] = self.problem.get_props(agent_id,new_vars[i])
used_solution = self.previous_solutions[agent_id]
penalty = 0
for i in range(meeting_size):
agent_id = agent_ids[i]
penalty += self.check_constraints(agent_id,new_vars[i])
if penalty > 0:
new_obj_func = penalty
else:
props,needs,targets,target_needs = self.get_solution_properties(used_solution,agent_ids,new_props,new_needs,new_targets,new_target_needs)
if props != -1:
#evaluate how the design performs with the last solution used as well; useful for stability
new_obj_func = self.evaluate_solution(props,needs,targets,target_needs)
else:
new_obj_func = self.PENALTY_SCORE
if self.timestep % self.spec_compiler_interval == 0 or new_obj_func == self.PENALTY_SCORE:
new_obj_ns, new_solution = self.design_compiler(agent_ids,new_props,new_needs,new_targets,new_target_needs)
if new_obj_ns < new_obj_func:
new_obj_func = new_obj_ns
used_solution = new_solution
for i in range(meeting_size):
agent_id = agent_ids[i]
self.team[agent_id].active_hist_solution.append(used_solution)
accept = self.team[agent_id].update_learn(new_obj_func - old_obj_func)
#update history for future temperature updates
self.team[agent_id].active_hist.append(new_obj_func)
self.team[agent_id].active_hist_needs.append(new_needs[i])
self.team[agent_id].active_hist_target_needs.append(new_target_needs[i])
self.team[agent_id].active_hist_design.append(new_vars[i])
if (len(self.team[agent_id].hist) > self.team[agent_id].hist_length):
self.team[agent_id].active_hist.pop(0)
self.team[agent_id].active_hist_needs.pop(0)
self.team[agent_id].active_hist_target_needs.pop(0)
self.team[agent_id].active_hist_design.pop(0)
if self.integration_mode == 1:
self.team[agent_id].active_hist_solution.pop(0)
self.team[agent_id].update_temp()
if (accept == 1):
for i in range(meeting_size):
agent_id = agent_ids[i]
self.wip[agent_id] = new_vars[i]
self.wip_needs[agent_id] = new_needs[i]
self.wip_target_needs[agent_id] = new_target_needs[i]
self.team[agent_id].move = move_id[i]
self.wip_props[agent_id] = new_props[i]
self.wip_targets[agent_id] = new_targets[i]
self.old_obj_funcs[agent_id] = new_obj_func
self.previous_solutions[agent_id] = used_solution
agent_id = agent_ids[0]
if self.meeting_timer[agent_id] >= self.meeting_length:
self.end_meeting(agent_id)
return
def end_meeting(self,agent_id):
agent_ids = self.meeting_with[agent_id]
for i in agent_ids:
#set statuses to show agents as in a meeting
self.is_communicating[i] = 0
self.meeting_with[i] = []
self.meeting_timer[i] = 0
merged_idx = self.merge_design(i, must_merge = True)
self.new_design(i)
return
#agent 1 requires that agent 2(s) fulfill the needs for one of its designs
def demanding_request(self,agent_1,agent_2s):
#ensure all requested agents are free
for i in agent_2s:
if self.is_communicating[i]:
return
active_idxs = np.nonzero(self.active_designs[agent_1])[0]
comm_obj_funcs = np.asarray([self.local_objective(agent_1,self.design_props[agent_1][i],self.design_needs[agent_1][i],self.design_targets[agent_1][i],self.target_needs[agent_1][i],use_distances = False) for i in active_idxs])
idx = random.choices(range(len(active_idxs)),np.exp(-(comm_obj_funcs-np.amin(comm_obj_funcs))))[0]
design_id = active_idxs[idx]
requested_goals = copy.deepcopy(self.problem.needs_bases)
requested_targets = copy.deepcopy(self.problem.target_need_bases)
working_agents = np.asarray([])
requested_goals[agent_1] = np.ma.asarray(copy.deepcopy(self.design_props[agent_1][design_id]))
requested_targets[agent_1] = np.ma.stack((np.ma.asarray(copy.deepcopy(self.design_targets[agent_1][design_id]))*(1-self.target_tol),np.ma.asarray(copy.deepcopy(self.design_targets[agent_1][design_id]))*(1+self.target_tol)),axis=-1)
for agent_2 in agent_2s:
requested_goals[agent_2] = np.ma.asarray(copy.deepcopy(self.design_needs[agent_1][design_id][agent_2]))
requested_targets[agent_2] = np.ma.asarray(copy.deepcopy(self.target_needs[agent_1][design_id][agent_2]))
#Have all participants take into account each others' needs when developing -
#this is needed to converge to the intersection of sets of all participants
goals_table = [copy.deepcopy(self.problem.needs_bases) for i in range(len(agent_2s))]
targets_table = [copy.deepcopy(self.problem.target_need_bases) for i in range(len(agent_2s))]
useable_designs = []
design_obj_funcs = []
used_idxs = np.zeros(len(agent_2s)).astype(int)
#find closest designs to the requester and propose them
temp_idx = list(np.zeros(len(agent_2s)))
#construct goals tables and check against the proposed agent 1 design
for i in range(len(agent_2s)):
agent_2 = agent_2s[i]
temp_idx[i] = self.merge_design(agent_2)
active_idxs = np.nonzero(self.active_designs[agent_2])[0]
goal_rank = np.asarray([self.check_goals(agent_2,self.design_props[agent_2][j],self.design_needs[agent_2][j],self.merge_goals(agent_2,requested_goals,self.design_goals[agent_2][j]),apply_penalty = False)+self.check_targets(agent_2,self.design_targets[agent_2][j],self.target_needs[agent_2][j],self.merge_targets(agent_2,requested_targets,self.target_goals[agent_2][j]),apply_penalty = False) for j in active_idxs])
#record which designs were used for later
useable_designs.append(active_idxs)
design_obj_funcs.append(comm_obj_funcs)
proposed_design = active_idxs[np.argmin(goal_rank)]
used_idxs[i] = proposed_design
#resulting design must satisfy needs of designs requesting it
prop_goal = copy.deepcopy(self.design_needs[agent_2][proposed_design])
target_goal = copy.deepcopy(self.target_needs[agent_2][proposed_design])
#resulting design cannot have needs beyond the properties of designs requesting it
need_goal = copy.deepcopy(self.design_props[agent_2][proposed_design])
target_need_goal = np.ma.stack((self.design_targets[agent_2][proposed_design]*(1-self.target_tol),self.design_targets[agent_2][proposed_design]*(1+self.target_tol)),axis=-1)
goals_table[i] = prop_goal
goals_table[i][agent_2] = np.ma.asarray(need_goal)
targets_table[i] = target_goal
targets_table[i][agent_2] = np.ma.asarray(target_need_goal)
#find if the proposed designs all work together
solution_found = 1
best_solution_value = 0
solution_value = 0
for i in range(len(agent_2s)):
agent_2 = agent_2s[i]
proposed_design = used_idxs[i]
#merge the table with the requesting design to get proposed goals
temp_goals = copy.deepcopy(requested_goals)
temp_targets = copy.deepcopy(requested_targets)
for j in range(len(agent_2s)):
temp_goals = self.merge_goals(agent_2,temp_goals,goals_table[j])
temp_targets = self.merge_targets(agent_2,temp_targets,targets_table[j], use_error = False)
#check if anyone can't meet the updated goals; invalid target merging will also result in violations
violation = self.check_goals(agent_2,self.design_props[agent_2][proposed_design],self.design_needs[agent_2][proposed_design],self.merge_goals(agent_2,temp_goals,self.design_goals[agent_2][proposed_design]),apply_penalty = False)+self.check_targets(agent_2,self.design_targets[agent_2][proposed_design],self.target_needs[agent_2][proposed_design],self.merge_targets(agent_2,temp_targets,self.target_goals[agent_2][proposed_design]),apply_penalty = False)
#if a design doesn't work, we go to problem solving
if violation > 0:
solution_found = 0
solution_value += violation
if solution_found == 0 and self.current_max_designs > 1:
#make initial population
solutions = ([self.random_solution(useable_designs) for i in range(self.compiler_starting_samples)])
solution_found = 0
best_solution_value = solution_value
requested_target_table = copy.deepcopy(targets_table)
requested_goal_table = copy.deepcopy(goals_table)
for i in range(self.max_compiler_iterations):
#check if any member of the population has compatible goals
for j in range(len(solutions)):
#make table...
for k in range(len(agent_2s)):
agent_2 = agent_2s[k]
proposed_design = solutions[j][k]
goals_table[k][agent_1] = np.ma.asarray(self.design_needs[agent_2][proposed_design][agent_1])
goals_table[k][agent_2] = np.ma.asarray(self.design_props[agent_2][proposed_design])
targets_table[k][agent_1] = np.ma.asarray(self.target_needs[agent_2][proposed_design][agent_1])
targets_table[k][agent_2] = np.ma.asarray(np.ma.stack((self.design_targets[agent_2][proposed_design]*(1-self.target_tol),self.design_targets[agent_2][proposed_design]*(1+self.target_tol)),axis=-1))
#score the combination
violation = 0
for k in range(len(agent_2s)):
agent_2 = agent_2s[k]
#merge and check goals...
temp_goals = copy.deepcopy(requested_goals)
temp_targets = copy.deepcopy(requested_targets)
for l in range(len(agent_2s)):
temp_goals = self.merge_goals(agent_2,temp_goals,goals_table[l])
temp_targets = self.merge_targets(agent_2,temp_targets,targets_table[l], use_error = False)
violation = violation + self.check_goals(agent_2,self.design_props[agent_2][proposed_design],self.design_needs[agent_2][proposed_design],self.merge_goals(agent_2,temp_goals,self.design_goals[agent_2][proposed_design]),apply_penalty = False)+self.check_targets(agent_2,self.design_targets[agent_2][proposed_design],self.target_needs[agent_2][proposed_design],self.merge_targets(agent_2,temp_targets,self.target_goals[agent_2][proposed_design]),apply_penalty = False)
#if no violators, we're done!
if violation == 0:
solution_found = 1
used_idxs = solutions[j]
requested_target_table = copy.deepcopy(targets_table)
requested_goal_table = copy.deepcopy(goals_table)
break
#else check if it beats the best found so far
elif violation < best_solution_value:
best_solution_value = violation
used_idxs = solutions[j]
requested_target_table = copy.deepcopy(targets_table)
requested_goal_table = copy.deepcopy(goals_table)
if solution_found == 1:
break
#change some subsystems around and see what we get
for j in range(len(solutions)):
options = useable_designs
solutions[j],changed_idx = self.change_random_subsystem(solutions[j],options)
#Everything already satisfies the goals!
else:
requested_target_table = copy.deepcopy(targets_table)
requested_goal_table = copy.deepcopy(goals_table)
for i in range(len(agent_2s)):
agent_2 = agent_2s[i]
proposed_design = used_idxs[i]
#merge the table with the requesting design to get proposed goals
final_goals = copy.deepcopy(requested_goals)
final_targets = copy.deepcopy(requested_targets)
for j in range(len(agent_2s)):
final_goals = self.merge_goals(agent_2,final_goals,requested_goal_table[j])
final_targets = self.merge_targets(agent_2,final_targets,requested_target_table[j])
#If all processes have failed, call the request a failure and return to work
#TODO - need better resolution in the problem solving as well
if final_targets == -1:
for j in range(len(agent_2s)):
if temp_idx[j] == -1 or temp_idx[j] == None:
self.new_design(agent_2)
else:
self.fork_design(agent_2,temp_idx[i]) #pick back up on original work (from best point)
return
#check if the agent already meets the combined goals
violation = self.check_goals(agent_2,self.design_props[agent_2][proposed_design],self.design_needs[agent_2][proposed_design],self.merge_goals(agent_2,final_goals,self.design_goals[agent_2][proposed_design])) + self.check_targets(agent_2,self.design_targets[agent_2][proposed_design],self.target_needs[agent_2][proposed_design],self.merge_targets(agent_2,final_targets,self.target_goals[agent_2][proposed_design]))
#if the agent already satisfies the requirements, just update their goals!
if violation == 0:
test_targets = self.merge_targets(agent_2,final_targets,self.target_goals[agent_2][proposed_design])
if test_targets == -1:
raise Exception("Test targets = -1 when it shouldnt!")
if self.integration_mode == 0:
self.target_goals[agent_2][proposed_design] = test_targets
self.design_goals[agent_2][proposed_design] = self.merge_goals(agent_2,final_goals,self.design_goals[agent_2][proposed_design])
if temp_idx[i] == -1 or temp_idx[i] == None:
self.new_design(agent_2)
else:
self.fork_design(agent_2,temp_idx[i]) #pick back up on original work (from best point)