-
Notifications
You must be signed in to change notification settings - Fork 0
/
ABM_server.py
2036 lines (1591 loc) · 63.4 KB
/
ABM_server.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
# coding: utf-8
# # test ABM with standard test functions
#
# In[1]:
import numpy as np
import scipy
import pandas as pd
from scipy.stats import chi
# from opteval import benchmark_func as bf
import matplotlib
import os
#for server:
matplotlib.use('Agg')
#for retina display:
# %config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import copy
import time as timer
import threading
import pickle
import multiprocessing
from multiprocessing import Pool
# from playsound import playsound
# from sklearn import linear_model
# ## Helper Functions
# In[2]:
def cp(x): #make a copy instead of reference
return copy.deepcopy(x)
def isNumber(s):
try:
float(s)
return True
except ValueError:
return False
def isNaN(num):
return num != num
def mean(x):
return np.mean(x)
def norm(x):
return float(np.linalg.norm(x))
def dist(x,y):
return np.linalg.norm(np.array(x)-np.array(y))
def bounds(x,low,high):
if x > high:
return high
if x < low:
return low
return x
def pScore(A,B):#ANOVA of 2 independent samples: are differences significant?
_, p = scipy.stats.ttest_ind(A,B)
return p
def aiColor(ai): #red for innovators, blue for adaptors
ai01 = bounds((ai - 40)/ 120,0,1)
red = ai01
blue = 1 - ai01
return (red,0,blue)
def makeAiScore():
ai = np.random.normal(97,17)
ai = bounds(ai, 40,150)
return ai
def makeIqScore(): #this IQ ranges from 0 to 1, bc it is basically efficiency
iq = np.random.normal(0.5,0.2)
iq = bounds(iq, 0.1,1.0)
return iq
def pickWorseScore(betterScore,worseScore,temperature):
if temperature <=1E-6: #never pick worse answers, and avoid devide by 0
return False
if np.random.uniform(0,1) < np.exp((betterScore-worseScore)/temperature): #
return True
return False
def calculateDecay(steps,T0=1.0,Tf=0.01):
if T0<=Tf or T0<=0:
return 0
return (Tf / float(T0) ) ** (1/steps)
def calculateAgentDecay(agent, steps):
E_N = normalizedE(agent.kai.E)
E_transformed = np.exp((E_N*-1)+2)
startEndRatio = bounds(1/E_transformed, 1E-10,1)
# print("ratio: %s" % startEndRatio)
T0 = agent.temp
TF = T0 * startEndRatio
return calculateDecay(steps,T0,TF)#, startEndRatio
# def chaching():
# playsound("./missionComplete.wav")
# In[3]:
# es = []
# kais = []
# ratios = []
# for i in range(500):
# a = Agent()
# d, ratio = calculateAgentDecay(a,100)
# es.append(a.kai.E)
# kais.append(a.kai.KAI)
# ratios.append(ratio)
# plt.scatter(es, ratios)
# plt.show()
# plt.scatter(kais, ratios)
# ## global constants and parameters
# In[4]:
complexSharing = True #if False, shareBasic() is used, eg strictly-greedy one-dimension jump
shareAcrossTeams = True
commBonus = 10 #increasing the communication bonus makes successful communication more likely
commRange = 180
pCommTime = None
selfBias = 0 #increasing self bias will make agents choose their solutions more over others
startRange = 1
nDims = 56
SO_STRENGTH = 10
RG_STRENGTH = 10
TEAM_MEETING_COST = 1 #1 turn
ROUGHNESS = .025
w_global = 100
VERBOSE = False
showViz = False
AVG_SPEED = 7.0E-3
SD_SPEED = 7.0E-4
MIN_SPEED = 1.0E-4
AVG_TEMP = 1
SD_TEMP = 0.5
UNIFORM_SPEED = False
UNIFORM_TEMP = False
startPositions = None
steps = 500 #0 #100
nAgents = 33
# constructor = Wteinway
pComm = 0.2
pCommTime = None
meetingTimes = steps #have one meeting at the end
startHavingMeetings = 0
# # Objectives
# In[5]:
#implement four classic test optimization functions, and my tuneable roughness one
# In[6]:
def objectiveTune(x,roughness=.05,w=100):
a = roughness
b = 2
x = np.array(x)
xEach = -1*a*np.sin((x*w+np.pi/2)) + b*(x*1.5)**2 + roughness #min is zero at zero vector
y = sum(xEach)
return y
# In[7]:
def constrain(x):
for i in range(len(x)):
x[i] = bounds(x[i],-1,1)
return x
# In[8]:
x = np.linspace(-1,1,1000)
for ROUGHNESS in [0,.2,3]:#np.linspace(0,.1,5):#= 0.05
y=[objectiveTune([xi],ROUGHNESS) for xi in x]
plt.plot(x,y)
plt.xlim([-.5,.5])
plt.ylim([0,2])
# In[9]:
x = np.linspace(-1,1,1000)
y=[objectiveTune([xi],0.2) for xi in x]
plt.plot(x,y)
plt.xlim([-.5,.5])
plt.ylim([0,2])
plt.savefig('./results/problem1.png',dpi=300)
plt.show()
x = np.linspace(-1,1,1000)
y=[objectiveTune([xi],5) for xi in x]
plt.plot(x,y)
plt.xlim([-.5,.5])
plt.ylim([0,20])
plt.savefig('./results/problem5.png',dpi=300)
# ## new objective
# In[10]:
# # def f1(x,p=1,c=0):
# # return (x+c)**p
# def generateComposite(ws,ps,cs):
# return lambda x: np.sum([ws[i]*(x-cs[i])**ps[i] for i in range(len(ws))])
# def generateConstraint(alpha,beta,gamma,i,j):
# return lambda x: alpha*((x[i]-gamma[0])**2+(x[j]-gamma[1])**2 - beta**2)
# def generateConstraint2(alpha,beta,gamma,nDims):
# return lambda x: alpha*(sum([(x[i]-gamma[i])**2 for i in range(nDims)]) - beta**2)
# def generateFunctionsNdims(n):
# allF = []
# for i in range(n):
# ws = np.random.uniform(-1,1,3)
# ws[2] = ws[2] * 10
# ps = [3,3,1]
# cs = np.random.uniform(-1,1,3)
# f = generateComposite(ws,ps,cs)
# allF.append(f)
# return allF
# #constraints: g(x)<= 0
# def generateConstraints(n,nDims):
# gs = []
# alphas = [-1,1]
# for i in range(n):
# alpha = alphas[i]#np.random.choice([-1,1]) #inside or outside
# beta = np.random.uniform(.3,.8) #size of circle
# gamma = np.random.uniform(-.2,.2,nDims)#2 #center of circle
# # i,j = np.random.choice(range(nDims),2,replace=False) #dimensions to constrain
# # g = generateConstraint(alpha,beta,gamma,i,j)
# g = generateConstraint2(alpha,beta,gamma,nDims)
# gs.append(g)
# return gs
# def evalX(fs,x,gs=[]):
# y = 0
# for i in range(len(x)):
# f = fs[i]
# y+= f(x[i])
# if abs(x[i]) > 1:
# return 1E18
# for g in gs: #composite constraints
# if g(x)>0:
# return 1E18
# return y
# def evalXpeacewise(fs,x,gs=[]):
# y = 0
# for i in range(len(x)):
# f = fs[i]
# y+= f(x[i])
# if abs(x[i]) > 1:
# return 1E18
# #make a peacewise domain:
# inDomain = False
# for g in gs: #if it satisfies ANY constraint, it passes
# if g(x)<=0:
# inDomain = True
# if not inDomain:
# return 1E18
# return y
# # crescentFs = generateFunctionsNdims(nDims)
# # crescentGs = generateConstraints(2,nDims)
# # Create Virtual Population with represntative KAI scores
# based on KAI score and subscore dataset provided by Dr. J
# In[11]:
kaiDF_DATASET = pd.read_csv("./KAI/KAI_DATA_2018_07_09.csv")
kaiDF_DATASET.columns = ["KAI","SO","E","RG"]
def makeKAI(n=1,asDF=True):
pop = np.random.multivariate_normal(kaiDF_DATASET.mean(),kaiDF_DATASET.cov(),n)
if asDF:
popDF = pd.DataFrame(pop)
popDF.columns = kaiDF_DATASET.columns
return popDF if n>1 else popDF.loc[0]
else:
return pop if n>1 else pop[0]
# def makeSubscores(kai,n=1,asDF=True):
# pop = np.random.multivariate_normal(kaiDF_DATASET.mean(),kaiDF_DATASET.cov(),n)
kaiPopulation = makeKAI(100000)
kaiPopulation=kaiPopulation.round()
def findAiScore(kai):
kai = int(kai)
a = kaiPopulation.loc[kaiPopulation['KAI'] == kai]
ind = np.random.choice(a.index)
me = kaiPopulation.loc[ind]
return KAIScore(me) #this is a KAIScore object
#calculate speed and temperature based on agents' KAI scores
def calcAgentSpeed(kai):
# speed = bounds(AVG_SPEED + normalizedAI(kai) * SD_SPEED, MIN_SPEED ,np.inf)
speed = bounds(np.exp(normalizedAI(kai))* AVG_SPEED, MIN_SPEED ,np.inf)
return speed
def calcAgentTemp(E):
# return bounds(AVG_TEMP + normalizedE(E) * SD_TEMP, 0 ,np.inf)
return np.exp(normalizedE(E)*AVG_TEMP)
#create standardized (not normalized) KAI scores and subscores
def normalizedAI(ai):
return (ai - kaiDF_DATASET.mean().KAI)/kaiDF_DATASET.std().KAI
def normalizedRG(rg):
return (rg - kaiDF_DATASET.mean().RG)/kaiDF_DATASET.std().RG
def normalizedE(E):
return (E - kaiDF_DATASET.mean().E)/kaiDF_DATASET.std().E
def normalizedSO(SO):
return (SO - kaiDF_DATASET.mean().SO)/kaiDF_DATASET.std().SO
# In[12]:
k= range(50,150)
s=[]
for i in k:
s.append(calcAgentSpeed(i))
plt.scatter(k,s)
calcAgentSpeed(98)
# In[13]:
def dotNorm(a,b): #return normalized dot product (how parallel 2 vectors are, -1 to 1)
if norm(a) <= 0 or norm(b)<= 0:
# print("uh oh, vector was length zero")
return 0
a = np.array(a)
b = np.array(b)
dotAB = np.sum(a*b)
normDotAB = dotAB / (norm(a)*norm(b))
return normDotAB
def plotCategoricalMeans(x,y):
categories = np.unique(x)
means = []
sds = []
for c in categories:
yc = [y[i] for i in range(len(y)) if x[i] == c]
means.append(np.mean(yc))
sds.append(np.std(yc))
plt.errorbar(categories,means,yerr=sds,marker='o',ls='none')
return means
#speed distributions:
dfConstant=1.9
def travelDistance(speed): #how far do we go? chi distribution, but at least go 0.1 * speed
r = np.max([chi.rvs(dfConstant),0.1])
return r * speed
def memoryWeightsPrimacy(n):
if n==1:
return np.array([1])
weights = np.arange(n-1,-1,-1)**3*0.4 + np.arange(0,n,1)**3
weights = weights / np.sum(weights)
return weights
# # machinery to save results
# In[14]:
def makeParamString():
s= ""
s+= "steps: "+ str(steps) + " \n"
s+= "self-bias: " +str(selfBias)+ " \n"
s+= "num agents: " +str(nAgents)+ " \n"
s+= "num teams: " +str(nTeams)+ " \n"
s+= "num dimensions: " +str(nDims)+ " \n"
s+= "rg strength: " +str(RG_STRENGTH)+ " \n"
s+= "so strength: " +str(SO_STRENGTH)+ " \n"
s+= "repeats: " +str(reps)+ " \n"
s+= "avg speed: " +str(AVG_SPEED) + " \n"
s+= "sd speed: " + str(SD_SPEED)+ " \n"
s+= "min speed: " +str(MIN_SPEED)+ " \n"
s+= "avg temp: "+ str(AVG_TEMP)+ " \n"
s+= "sd temp: " +str(SD_TEMP)+ " \n"
s+= "roughness: " +str(ROUGHNESS)+ " \n"
return s
class Result:
def __init__(self):
self.bestScore = np.inf
self.bestCurrentScore = np.inf
self.nMeetings = 0
self.agentKAIs = []
def saveResults(teams,dirName='',url='./results'):
directory = url+'/'+str(timer.time())+dirName
os.mkdir(directory)
paramsURL = directory+'/'+'parameters.txt'
np.savetxt(paramsURL,[makeParamString()], fmt='%s')
teamResults = []
for team in teams:
result = Result()
result.bestScore = team.getBestScore()
result.bestCurrentScore = team.getBestCurrentScore()
result.nMeetings = team.nMeetings
result.agentKAIs = [a.kai for a in team.agents]
teamResults.append(result)
rFile = directory+'/'+'results.obj'
rPickle = open(rFile, 'wb')
pickle.dump(teamResults, rPickle)
return directory
# In[15]:
# directory = saveResults(saveTeams, 'trial')
# filehandler = open(directory+'/results.obj', 'rb')
# returnedObj = pickle.load(filehandler)
# plt.scatter([0,1],[2,3])
# plt.savefig(directory+'/fig.pdf')
# ## Agent and Team Classes
# In[16]:
class Agent:
def __init__(self, id=-1):
self.id = id
self.score = np.inf
self.r = np.random.uniform(-1,1,size=nDims)
self.nmoves = 0
self.kai = KAIScore()
self.speed = calcAgentSpeed(self.kai.KAI)
self.temp = calcAgentTemp(self.kai.E)
self.iq = 1 #makeIqScore()
self.memory = [Solution(self.r,self.score,self.id,type(self))]
self.team = -1
self.decay = calculateAgentDecay(self,100)
self.startTemp = cp(self.temp)
self.startSpeed = cp(self.speed)
def reset(self):
self.temp = self.startTemp
self.speed = calcAgentSpeed(self.kai.KAI)
self.memory = []
self.r = np.random.uniform(-1,1,size=nDims)
self.nmoves = 0
self.score = np.inf
def move(self,soBias=False,groupConformityBias=False,teamPosition=None):
if np.random.uniform()>self.iq: #I'm just thinking this turn
return False
# print("my dimensions:" +str(self.myDims))
#pick a new direction
d = np.random.uniform(-1,1,nDims)
d = d * self.myDims #project onto the dimensions I can move
dn = np.linalg.norm(d)
if dn==0: print("divide by zero (dn)")
#distance moved should be poisson distribution, rn its just my speed
distance = travelDistance(self.speed) * nDims
d = d / dn * distance
# print('considering moving '+str(d) + ' from '+str(self.r))
candidateSolution = (self.r + d)
candidateSolution = constrain(candidateSolution)
acceptsNewSolution = self.evaluate(candidateSolution,soBias,groupConformityBias,teamPosition=teamPosition)
if acceptsNewSolution:
self.moveTo(candidateSolution)
return True
# self.score = self.f()
return False
def moveTo(self, r):
self.r = r
self.score = self.f()
self.memory.append(Solution(self.r,self.score,self.id,type(self)))
self.nmoves += 1
def startAt(self,position):
self.r = position
self.memory = [Solution(r=self.r,score=self.f(),owner_id=self.id,agent_class=type(self))]
def wantsToTalk(self,pComm):
if(np.random.uniform() < pComm):
return True
return False
def getBestScore(self):
bestScore = self.score
for s in self.memory:
if s.score < bestScore:
bestScore = s.score
return bestScore
def getBestSolution(self):
bestSolution = cp(self.memory[0])
for m in self.memory:
if m.score < bestSolution.score:
bestSolution = m
return bestSolution
def soBias(self,currentPosition,candidatePosition): #influences preference for new solutions, f(A-I)
#positions should be given as NORMALIZED positions on unit cube!
soNorm = normalizedSO(self.kai.SO) #normalized score for Sufficiency of Originality
memSize = len(self.memory)
if memSize < 2: return 0 #we don't have enough places be sticking around them
candidateDirection = candidatePosition - currentPosition #in unit cube space
memDirection = 0 # what is the direction of past solns from current soln?
weights = memoryWeightsPrimacy(memSize) #weights based on temporal order, Recency and Primacy Bias
for i in range(memSize-1): #don't include current soln
past_soln = self.memory[i]
pairwiseDiff = past_soln.r - currentPosition
memDirection += pairwiseDiff * weights[i]
#now we see if the new solution is in the direction of the memories or away from the memories
paradigmRelatedness = dotNorm(memDirection, candidateDirection)
raw_PR_score = soNorm * (paradigmRelatedness + 0) #shifting the x intercept #biasOfSO(PR,soNorm)
sufficiency_of_originality = raw_PR_score*SO_STRENGTH #the agent should have a memory of their path & interactions
return sufficiency_of_originality
def groupConformityBias(self,teamPosition,currentPosition,candidatePosition): #influences preference for new solutions, f(A-I)
rgNorm = normalizedRG(self.kai.RG) #normalized score for Rule/Group Conformity
candidateDirection = candidatePosition - currentPosition
#all teammates have equal weight
teamDirection = teamPosition - currentPosition
#now we see if the new solution is in the direction of the team or away from the team
groupConformity = dotNorm(teamDirection, candidateDirection)
nominalGC = 0 #can change intercept with -0 (using dot product of direction,so is perpendicular the null case?)
groupConformityBias = (groupConformity-nominalGC)*rgNorm*RG_STRENGTH
return groupConformityBias
def evaluate(self,candidateSolution,soBias=False,groupConformityBias=False,teamPosition=None): #implements simulated annealing greediness
candidateScore = self.fr(candidateSolution)
if soBias:
candidateScore += self.soBias(self.r,candidateSolution)
if groupConformityBias:
gcB = self.groupConformityBias(teamPosition,self.r,candidateSolution)
candidateScore += gcB
#if better solution, accept
if candidateScore < self.score:
return True
#accept worse solution with some probability, according to exp((old-new )/temp)
elif pickWorseScore(self.score,candidateScore,self.temp):
self.score = candidateScore #(its worse, but we go there anyways)
return True
return False
#Solutions are objects
class Solution():
def __init__(self, r, score, owner_id=None, agent_class=None):
self.r = cp(r)
# self.rNorm = self.r / scalingVector
self.score = cp(score)
self.owner_id = cp(owner_id)
self.agent_class = cp(agent_class)
#KAI scores are objects
class KAIScore():
def __init__(self,subscores=None):
if subscores is None:
subscores = makeKAI(1,True)
self.KAI = subscores.KAI
self.SO = subscores.SO
self.E = subscores.E
self.RG = subscores.RG
class Crescent(Agent): #randomized functions and constraints
def __init__(self, id=-1):
Agent.__init__(self,id)
self.myDims = np.ones(nDims)
# self.r = np.random.uniform(-1*startRange,startRange,nDims)
def f(self):
return evalX(crescentFs,self.r,crescentGs)
def fr(self,r):
return evalX(crescentFs,r,crescentGs)
class PeaceWise(Agent): #randomized functions and constraints
def __init__(self, id=-1):
Agent.__init__(self,id)
self.myDims = np.ones(nDims)
# self.r = np.random.uniform(-1*startRange,startRange,nDims)
def f(self):
return evalXpeacewise(crescentFs,self.r,crescentGs)
def fr(self,r):
return evalXpeacewise(crescentFs,r,crescentGs)
class Steinway(Agent): #tuneable roughness
def __init__(self, id=-1):
Agent.__init__(self,id)
self.myDims = np.ones(nDims)
# self.r = np.random.uniform(-1*startRange,startRange,nDims)
def f(self):
return objectiveTune(self.r,ROUGHNESS,w_global)
def fr(self,r):
return objectiveTune(r,ROUGHNESS,w_global)
def tryToShare(a1,a2):
deltaAi = abs(a1.kai.KAI - a2.kai.KAI) #harder to communicate above 20, easy below 10
deltaR = np.linalg.norm(a1.r - a2.r)
successful = tryComm(deltaAi,deltaR)
if successful: #in share(), agents might adopt a better solution depending on their temperature
share(a1,a2) if complexSharing else shareBasic(a1,a2)
return True
return False
def shareBasic(a1,a2): #agents always go to better solution
if a1.score < a2.score:
a2.moveTo(a1.r)
elif a2.score < a1.score:
a1.moveTo(a2.r)
return True
def share(a1,a2): #agent chooses whether to accept new solution or not, holistic NOTTTTTT dimension by dimension
copyOfA1 = cp(a1)
considerSharedSoln(a1,a2)
considerSharedSoln(a2,copyOfA1) #so they could theoretically swap positions...
return True
def considerSharedSoln(me,sharer): #,dim): #will only move (jump) in the dimensions that sharer controls
# candidateSoln = me.r #other dimensions won't change
# candidateSoln[dim] = sharer.r[dim] #tells a1 where to go in This [i] dimension only
candidateSolution = sharer.r
candidateScore = me.fr(candidateSolution)
myScore = me.score - selfBias #improve my score by selfBias
#Quality Bias Reduction? would go here
if(candidateScore<myScore):
if not pickWorseScore(candidateScore,myScore,me.temp): #sometimes choose better, not always
me.moveTo(candidateSolution) #(but never take a worse score from a teammate)
# me.speed = me.startSpeed
# me.temp = me.startTemp # !! CHRIS trying somethign new here: restart temp at teammate's soln
constructor = Steinway
# In[17]:
# commBonus = 0
# commRange = 180
hardShareDist = 0
def tryComm(deltaAi,deltaR= 0 ):
c = np.random.uniform(commBonus,commBonus+commRange) #increasing commBonus makes sharing easier
#sharing can also fail when distance is far
spaceSize = np.sqrt(nDims)
d = np.random.uniform(spaceSize,spaceSize*hardShareDist)
return (deltaAi < c and deltaR < d)
# In[18]:
class Team(): #a group of agents working on the same dimension and objective function
def __init__(self, nAgents, agentConstructor, dimensions = np.ones(nDims), specializations = None, temp=None,speed=None,aiScore=None,aiRange=None,startPositions=None):
self.agents = []
self.dimensions = dimensions
if (aiScore is not None) and (aiRange is not None):
minScore = np.max([40, aiScore-aiRange/2.0])
maxScore = np.min([150,aiScore+aiRange/2.0])
aiScores = np.linspace(minScore,maxScore,nAgents)
np.random.shuffle(aiScores) #randomly assign these to agents, not in order...
#or we could try putting them in subteams according to a rule:
for i in range(nAgents):
a = agentConstructor(id = i)
if startPositions is not None:
a.startAt(startPositions[i])
if (aiScore is not None) and (aiRange is not None):
aiScore = aiScores[i]
a.kai = findAiScore(aiScore)
a.speed = calcAgentSpeed(a.kai.KAI)
a.temp = calcAgentTemp(a.kai.E)
if speed is not None:
a.speed = speed
if temp is not None:
a.temp = temp
a.startSpeed = a.speed
a.startTemp = a.temp
a.myDims = dimensions #default: all dimensions owned by every agent
if UNIFORM_SPEED:
a.speed = AVG_SPEED
self.agents.append(a)
self.nAgents = nAgents
aiScores = [a.kai.KAI for a in self.agents]
self.dAI = np.max(aiScores)- np.min(aiScores)
self.nMeetings = 0
self.shareHistory = []
self.nTeamMeetings = 0
self.subTeamMeetings = 0
self.meetingDistances = []
self.scoreHistory = []
#if there are subteams owning certain dimensions, each subteams dimensions are listed in a matrix
self.specializations = specializations
def reset(self):
self.nMeetings = 0
self.shareHistory = []
self.nTeamMeetings = 0
self.subTeamMeetings = 0
self.meetingDistances = []
for a in self.agents:
a.reset()
self.scoreHistory = []
def run(self,soBias=False,groupConformityBias=False):
np.random.seed()
i = 0 #not for loop bc we need to increment custom ammounts inside loop
while i < steps:
self.nMeetings += self.step(pComm,showViz,soBias,groupConformityBias)
if (i+1)%meetingTimes == 0:
cost = self.haveInterTeamMeeting()
i += cost #TEAM_MEETING_COST
i += 1
def getSharedPosition(self): #this is in the normalized space
positions = np.array([a.r for a in self.agents])
return [np.mean(positions[:,i]) for i in range(len(positions[0]))]
def getSubTeamPosition(self,team): #this is in the normalized space
positions = np.array([a.r for a in self.agents if a.team == team])
return [np.mean(positions[:,i]) for i in range(len(positions[0]))]
def getBestScore(self):
return np.min([a.getBestScore() for a in self.agents])
def getBestCurrentScore(self):
return np.min([a.score for a in self.agents])
def getBestSolution(self):
allSolns = [a.getBestSolution() for a in self.agents]
allScores = [s.score for s in allSolns]
return allSolns[np.argmin(allScores)]
def getBestCurrentSolution(self):
allSolns = [a.memory[-1] for a in self.agents]
allScores = [s.score for s in allSolns]
return allSolns[np.argmin(allScores)]
def getBestTeamSolution(self,team=-1): #returns a Solution object
bestIndividualSolns = [a.getBestSolution() for a in self.agents if a.team == team ]
bestScoreLocation = np.argmin([s.score for s in bestIndividualSolns])
return bestIndividualSolns[bestScoreLocation]
def getBestCurrentTeamSolution(self,team=-1): #returns a Solution object
individualSolns = [a.memory[-1] for a in self.agents if a.team == team ]
bestScoreLocation = np.argmin([s.score for s in individualSolns])
return individualSolns[bestScoreLocation]
def haveMeetings(self,talkers):
nMeetings = 0
for i in np.arange(0,len(talkers)-1,2):
a1 = talkers[i]
a2 = talkers[i+1]
didShare = tryToShare(a1,a2)
if didShare:
# print(str(a1.id) + ' and '+str(a2.id)+' shared!')
nMeetings +=1
self.nMeetings += nMeetings
self.shareHistory.append(nMeetings)
return nMeetings
def haveTeamMeeting(self):
#they all go to the best CURRENT position of the group
bestSolution = self.agents[0].memory[-1]
for a in self.agents:
agentCurrent = a.memory[-1]
if agentCurrent.score < bestSolution.score:
bestSolution = agentCurrent
#now move all agents to this position
for a in self.agents:
a.moveTo(bestSolution.r)
return bestSolution
def haveSubTeamMeeting(self,team,gap=False):
#they all go to the best position of their specialized team
teamAgents = [a for a in self.agents if a.team == team]
if gap: #the meeting might fail if the cognitive style gap is large
#take the KAI differences of the team into account
kaiScores = [a.kai.KAI for a in teamAgents]
deltaAi = max(kaiScores) - min(kaiScores) #hard to communicate above 20, easy below 10
successful = tryComm(deltaAi)
if not successful: #in share(), agents might adopt a better solution depending on their temperature
return None #our cognitive style gap caused the meeting to fail (only if complexSharing=True)
#ok, phew, we have a successful meeting despite any cognitive gap:
bestSolution = teamAgents[0].memory[-1]
for a in teamAgents:
agentCurrent = a.memory[-1]
if agentCurrent.score < bestSolution.score:
bestSolution = agentCurrent
#now move all agents to this position
for a in teamAgents:
a.moveTo(bestSolution.r)
return bestSolution
def haveInterTeamMeeting(self): #when you have teams of teams
allPositions = [a.r for a in self.agents]
teamDistance_Sum = sum(scipy.spatial.distance.pdist(allPositions))
# print(teamDistance_Sum)
#how much does the meeting cost? increases with distance
cost = min(int(teamDistance_Sum / nDims),15)
# print(cost)
#if the meeting takes to long, does it fail?
# if cost
consensusPosition = np.zeros(nDims)
#get the best solution from each specialized subteam, and extract their specialized dimensions
for team in range(len(self.specializations)):
bestTeamSoln = self.getBestCurrentTeamSolution(team)
specializedInput = bestTeamSoln.r * self.specializations[team]
consensusPosition += specializedInput
consensusPosition = constrain(consensusPosition)
consensusScore = self.agents[0].fr(consensusPosition)
#calculate how far everyone had to move
individualDistances = allPositions-consensusPosition
meetingDistance = np.mean(scipy.spatial.distance.pdist(individualDistances))
kaiDistance = np.mean(scipy.spatial.distance.pdist([[a.kai.KAI] for a in self.agents]))/100
self.meetingDistances.append(meetingDistance*kaiDistance)
#now move all agents to this position
for a in self.agents:
a.moveTo(consensusPosition)
self.nTeamMeetings += 1
return cost #[consensusScore, consensusPosition]
# def step(self,pComm,showViz=False,soBias=False,groupConformityBias=False):
# #what happens during a turn for the team?
# #each agents can problem solve or interact
# talkers = []
# #for speed, pre-calculate the team positions
# subTeamPositions = [None for i in range(len(self.specializations))]
# if groupConformityBias:
# subTeamPositions = [self.getSubTeamPosition(i) for i in range(len(self.specializations))]
# for a in self.agents:
# if a.wantsToTalk(pComm):
# talkers.append(a)
# else:
# teamPosition = subTeamPositions[a.team]#self.getSubTeamPosition(a.team) if groupConformityBias else None #position is on unit cube
# didMove = a.move(soBias=soBias,groupConformityBias = groupConformityBias, teamPosition=teamPosition)
# if len(talkers)%2>0: #odd number, have last one explore instead of share
# a = talkers.pop()
# teamPosition = subTeamPositions[a.team]#self.getSubTeamPosition(a.team) if groupConformityBias else None #position is on unit cube
# didMove = a.move(soBias=soBias,groupConformityBias = groupConformityBias, teamPosition=teamPosition)
# nMeetings = self.haveMeetings(talkers)
# # print("number of successful meetings: "+str(nMeetings))
# # if showViz:
# # self.plotPositions()
# self.updateTempSpeed()
# return nMeetings
#restrict pairwise sharing to sub-team only!
def step(self,pComm,showViz=False,soBias=False,groupConformityBias=False):
#what happens during a turn for the team?
#each agents can problem solve or interact
#for speed, pre-calculate the team positions
subTeamPositions = [None for i in range(len(self.specializations))]
if groupConformityBias:
subTeamPositions = [self.getSubTeamPosition(i) for i in range(len(self.specializations))]
nMeetings = 0
if shareAcrossTeams: #agents can communicate with anyone in the org
talkers = []
for a in self.agents:
if a.wantsToTalk(pComm):
talkers.append(a)
else:
teamPosition = subTeamPositions[a.team]#self.getSubTeamPosition(a.team) if groupConformityBias else None #position is on unit cube
didMove = a.move(soBias=soBias,groupConformityBias = groupConformityBias, teamPosition=teamPosition)
if len(talkers)%2>0: #odd number, have last one explore instead of share
a = talkers.pop()
teamPosition = subTeamPositions[a.team]#self.getSubTeamPosition(a.team) if groupConformityBias else None #position is on unit cube
didMove = a.move(soBias=soBias,groupConformityBias = groupConformityBias, teamPosition=teamPosition)
nMeetings += self.haveMeetings(talkers)
else: #agents can only communicate with other agents in their sub-team
#loop through the subteams:
for team in range(len(self.specializations)):
talkers = []
subTeamAgents = [a for a in self.agents if a.team == team]
for a in subTeamAgents:
if a.wantsToTalk(pComm):
talkers.append(a)
else:
teamPosition = subTeamPositions[a.team]#self.getSubTeamPosition(a.team) if groupConformityBias else None #position is on unit cube
didMove = a.move(soBias=soBias,groupConformityBias = groupConformityBias, teamPosition=teamPosition)
if len(talkers)%2>0: #odd number, have last one explore instead of share
a = talkers.pop()
teamPosition = subTeamPositions[a.team]#self.getSubTeamPosition(a.team) if groupConformityBias else None #position is on unit cube
didMove = a.move(soBias=soBias,groupConformityBias = groupConformityBias, teamPosition=teamPosition)
nMeetings += self.haveMeetings(talkers)
self.updateTempSpeed()
return nMeetings
def updateTempSpeed(self):
for a in self.agents:
a.temp *= a.decay
a.speed *= a.decay
def plotPositions(self):
xs = [a.r[0] for a in self.agents]
ys = [a.r[1] for a in self.agents]
cs = [aiColor(a.kai.KAI) for a in self.agents]
plt.scatter(xs,ys, c=cs)
# teamPosition = self.getSharedPosition()
# plt.scatter(teamPosition[0],teamPosition[1],c='orange')
# ## Tune Comm Bonus
# In[19]:
deltaAis = np.linspace(0,100,100)
# pSuccess = []
# for deltaAi in deltaAis: #hard to communicate above 20, easy below 10
# successful = []
# for i in range(1000):
# successful.append(tryComm(deltaAi))
# pSuccess.append(np.mean(successful))
theoreticalP = [min(1 - (d-10)/180,1) for d in deltaAis]
plt.plot(deltaAis,theoreticalP)
# plt.plot(deltaAis,pSuccess)
plt.xlabel("difference in KAI")
plt.ylabel("probability that communication succeeds")