-
Notifications
You must be signed in to change notification settings - Fork 0
/
embodied_ising.py
2069 lines (1599 loc) · 71.2 KB
/
embodied_ising.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 plotting
import numpy as np
import operator
from itertools import combinations, product
# import matplotlib as mpl
# mpl.use('Agg')
import matplotlib.pyplot as plt
import copy
from math import atan2
from math import cos
from math import degrees
from math import floor
from math import radians
from random import random
from random import sample
from random import randint
from math import sin
from math import sqrt
from random import uniform
from copy import deepcopy
import multiprocessing as mp
import sys
import os
import pickle
import time
#import random
from tqdm import tqdm
from shutil import copyfile
from numba import jit
# ------------------------------------------------------------------------------+
# ------------------------------------------------------------------------------+
# --- CLASSES ------------------------------------------------------------------+
# ------------------------------------------------------------------------------+
# ------------------------------------------------------------------------------+
settings = {}
class ising:
# Initialize the network
def __init__(self, settings, netsize, Nsensors=2, Nmotors=2, name=None): # Create ising model
self.size = netsize
self.Ssize = Nsensors # Number of sensors
self.Msize = Nmotors # Number of sensors
self.radius = settings['org_radius']
self.h = np.zeros(netsize) #
# self.J = np.zeros((self.size, self.size))
self.J = np.random.random((self.size, self.size))*2 - 1
self.J = (self.J + self.J.T) / 2 #Connectivity Matrix
np.fill_diagonal(self.J, 0)
self.max_weights = 2
self.maxRange = sqrt((settings['x_max'] - settings['x_min']) ** 2 +
(settings['y_max'] - settings['y_min']) ** 2)
self.randomize_state()
self.xpos = 0.0 # Position
self.ypos = 0.0
self.randomize_position(settings) #randomize position
# self.r = uniform(0, 360) # orientation [0, 360]
# self.v = uniform(0, settings['v_max']/3) # velocity [0, v_max]
# self.dv = uniform(-settings['dv_max'], settings['dv_max']) # dv
self.dx = 0
self.dy = 0
self.name = name
self.generation = 0
'''
initial beta
'''
self.Beta = settings['init_beta']
#self.Beta = 1.0
# self.defaultT = max(100, netsize * 20)
self.Ssize1 = 1 # FOOD ROTATIONAL SENSOR: sigmoid(theta)
self.Ssize2 = 1 # FOOD DISTANCE SENSOR: sigmoid(distance)
self.Ssize3 = 1 # DIRECTIONAL NEIGHBOUR SENSOR: dot-product distance normalized, see self.org_sens
self.Msize1 = int(self.Msize/2) # dv motor neuron
# MASK USED FOR SETTINGS J/h TO 0
self.maskJ = np.ones((self.size, self.size), dtype=bool)
self.maskJ[0:self.Ssize, 0:self.Ssize] = False
self.maskJ[-self.Msize: -self.Msize] = False
self.maskJ[0:self.Ssize, -self.Msize:] = False
np.fill_diagonal(self.maskJ, 0)
self.maskJ = np.triu(self.maskJ)
self.J[~self.maskJ] = 0
# self.maskJtriu = np.triu(self.maskJ)
self.disconnect_hidden_neurons(settings)
self.maskh = np.ones(self.size, dtype=bool)
self.maskh[0:self.Ssize] = False
self.m = np.zeros(self.size)
self.d_food = self.maxRange # distance to nearest food
self.r_food = 0 # orientation to nearest food
self.org_sens = 0 # directional, 1/distance ** 2 weighted organism sensor
self.fitness = 0
self.energy = 0.0
self.food = 0
self.energies = [] #Allows for using median as well... Replace with adding parameter up for average in future to save memory? This array is deleted before saving to reduce file size
self.avg_energy = 0
self.all_velocity = 0
self.avg_velocity = 0
self.v = 0.0
if settings['share_food']:
self.foodfound = 0
self.foodshared = 0
self.foodgiven = 0
self.assign_critical_values(settings)
# if not settings['BoidOn']:
# self.Update(settings, 0)
def reset_state(self, settings):
# randomize internal state (not using self.random_state since it also randomizes sensors)
self.s = np.random.random(size=self.size) * 2 - 1
self.m = np.zeros(self.size)
# randomize position (not using self.randomize_position function since it also randomizes velocity)
self.xpos = uniform(settings['x_min'], settings['x_max']) # position (x)
self.ypos = uniform(settings['y_min'], settings['y_max']) # position (y)
self.dv = 0
self.v = 0
self.ddr = 0
self.dr = 0
self.food = 0
self.fitness = 0
if settings['energy_model']:
self.energies = [] # Clear .energies, that .avg_energy is calculated from with each iteration
self.energy = settings['initial_energy'] # Setting initial energy
self.avg_energy = 0
self.all_velocity = 0
self.avg_velocity = 0
if settings['share_food']:
self.foodfound = 0
self.foodshared = 0
self.foodgiven = 0
def get_state(self, mode='all'):
if mode == 'all':
return self.s
elif mode == 'motors':
return self.s[-self.Msize:]
elif mode == 'sensors':
return self.s[0:self.Ssize]
elif mode == 'non-sensors':
return self.s[self.Ssize:]
elif mode == 'hidden':
return self.s[self.Ssize:-self.Msize]
def get_state_index(self, mode='all'):
return bool2int(0.5 * (self.get_state(mode) + 1))
# Randomize the state of the network
def randomize_state(self):
self.s = np.random.randint(0, 2, self.size) * 2 - 1
self.s = np.array(self.s, dtype=float)
# SEE SENSOR UPDATE
# random sensor states are generated by considering the sensor limitations
random_rfood = (np.random.rand() * 360) - 180
self.s[0] = random_rfood / 180
random_dfood = np.random.rand() * self.maxRange
self.s[1] = np.tanh(self.radius / (random_dfood ** 2 + 1e-6)) * 2 - 1
random_dorg = np.random.rand() * self.maxRange
self.s[2] = np.tanh(random_dorg) * 2 - 1
def randomize_position(self, settings):
'''
Only used in TimeEvolve2
'''
self.xpos = uniform(settings['x_min'], settings['x_max']) # position (x)
self.ypos = uniform(settings['y_min'], settings['y_max']) # position (y)
if settings['BoidOn']:
self.v = (np.random.randn(2) * 2 - 1) * settings['v_max']
self.dv = (np.random.randn(2) * 2 - 1) * settings['dv_max']
self.dx = self.v[0] * settings['dt']
self.dy = self.v[1] * settings['dt']
# self.r = np.abs(np.arctan(self.ypos / self.xpos))
self.r = np.arctan2(self.v[1], self.v[0]) * 180 / np.pi
'''
If 'BoidOn' == False self.r is undefined (it is defined in the upper if condition)
--> fixed by moving definition of self.r up in else condition
'''
else:
self.r = np.random.rand() * 360
self.v = np.random.rand() * settings['v_max'] #TODO: This cannot work with huge v_max
self.dv = np.random.rand() * settings['dv_max']
self.dx = self.v * cos(radians(self.r)) * settings['dt']
self.dy = self.v * sin(radians(self.r)) * settings['dt']
'''
NOT USED
# Set random bias to sets of units of the system
def random_fields(self, max_weights=None):
if max_weights is None:
max_weights = self.max_weights
self.h[self.Ssize:] = max_weights * (np.random.rand(self.size - self.Ssize) * 2 - 1)
'''
# Set random connections to sets of units of the system
def random_wiring(self, max_weights=None): # Set random values for h and J
if max_weights is None:
max_weights = self.max_weights
for i in range(self.size):
for j in np.arange(i + 1, self.size):
if i < j and (i >= self.Ssize or j >= self.Ssize):
self.J[i, j] = (np.random.rand(1) * 2 - 1) * self.max_weights
def updateAcceleration(self):
self.ddr = (np.sum(self.s[-self.Msize:-self.Msize1]) / 2)
self.dv = (np.sum(self.s[-self.Msize1:]) / 2)
def updateVelocity(self, settings):
self.updateAcceleration()
self.ddr = self.ddr * settings['ddr_max'] * settings['dt']
self.dv = self.dv * settings['dv_max'] * settings['dt']
if settings['energy_model']:
energy_cost = self.dv * settings['cost_speed']
if self.energy >= energy_cost and self.dv > settings['dv_min']:
#if agent has enough energy and wants to accelerate faster than the "free" acceleration
self.energy -= energy_cost
elif self.dv > settings['dv_min']:
#if agent wants to go faster than min speed but does not have energy
self.dv = settings['dv_min']
# UPDATE VELOCITY - Motor neuron s.[-self.Msize1:]
self.v += self.dv - settings['friction'] * self.v**2
self.dr += self.ddr - settings['friction'] * np.sign(self.dr)*self.dr
if self.v < 0:
self.v = 0
if self.v > settings['v_max']:
self.v = settings['v_max']
if settings['energy_model']:
self.all_velocity += self.v
if np.abs(self.dr) > settings['dr_max']:
self.dr = settings['dr_max']
def Move(self, settings):
self.updateVelocity(settings)
# UPDATE POSITION
self.dx = self.v * cos(radians(self.r)) * settings['dt']
self.dy = self.v * sin(radians(self.r)) * settings['dt']
self.xpos += self.dx
self.ypos += self.dy
# print(self.dx, self.dy)
# UPDATE HEADING
self.r += self.dr
self.r = self.r % 360
# periodic boundary conditions.
self.xpos = (self.xpos + settings['x_max']) % settings['x_max']
self.ypos = (self.ypos + settings['y_max']) % settings['y_max']
def MoveOld(self, settings):
self.r += (np.sum(self.s[-self.Msize:-self.Msize1]) / 2) * settings['dr_max'] * settings['dt']
self.r = self.r % 360
self.dv = (np.sum(self.s[-self.Msize1:]) / 2) * settings['dv_max'] * settings['dt']
self.v += self.dv
if self.v < 0:
self.v = 0
if self.v > settings['v_max']:
self.v = settings['v_max']
if settings['energy_model']:
energy_cost = self.v * settings['cost_speed']
if self.energy >= energy_cost and self.v > settings['v_min']:
#if agent has enough energy and wants to accelerate faster than the "free" acceleration
self.energy -= energy_cost
elif self.v > settings['v_min']:
#if agent wants to go faster than min speed but does not have energy
self.v = settings['v_min']
self.all_velocity += self.v
#############################
# UPDATE POSITION
self.dx = self.v * cos(radians(self.r)) * settings['dt']
self.dy = self.v * sin(radians(self.r)) * settings['dt']
self.xpos += self.dx
self.ypos += self.dy
# print(self.dx, self.dy)
# UPDATE HEADING
self.r += self.dr
self.r = self.r % 360
# periodic boundary conditions.
self.xpos = (self.xpos + settings['x_max']) % settings['x_max']
self.ypos = (self.ypos + settings['y_max']) % settings['y_max']
def MoveVelMotors(self, settings):
self.r += (np.sum(self.s[-self.Msize:-self.Msize1]) / 2) * settings['dr_max'] * settings['dt']
self.r = self.r % 360
self.v = (np.sum(self.s[-self.Msize1:]) / 2) * settings['v_max'] * settings['dt']
if self.v < 0:
self.v = 0
# if self.v > settings['v_max']:
# self.v = settings['v_max']
if settings['energy_model']:
energy_cost = self.v * settings['cost_speed']
if self.energy >= energy_cost and self.v > settings['v_min']:
#if agent has enough energy and wants to accelerate faster than the "free" acceleration
self.energy -= energy_cost
elif self.v > settings['v_min']:
#if agent wants to go faster than min speed but does not have energy
self.v = settings['v_min']
self.all_velocity += self.v
#############################
# UPDATE POSITION
self.dx = self.v * cos(radians(self.r)) * settings['dt']
self.dy = self.v * sin(radians(self.r)) * settings['dt']
self.xpos += self.dx
self.ypos += self.dy
# print(self.dx, self.dy)
# UPDATE HEADING
self.r += self.dr
self.r = self.r % 360
# periodic boundary conditions.
self.xpos = (self.xpos + settings['x_max']) % settings['x_max']
self.ypos = (self.ypos + settings['y_max']) % settings['y_max']
def UpdateSensors(self, settings):
# self.s[0] = sigmoid(self.r_food / 180)
# self.s[1] = sigmoid(self.d_food)
# normalize these values to be between -1 and 1
# TODO: make the numberators (gravitational constants part of the connectivity matrix so it can be mutated)
self.s[0] = self.r_food / 180 # self.r_food can only be -180:180
# self.s[1] = np.tanh(np.log10(self.radius / (self.d_food ** 2 + 1e-6))) # self.d_food goes from 0 to ~
# self.s[2] = np.tanh(np.log10(self.org_sens + 1e-10))
self.s[1] = np.tanh(self.radius / (self.d_food ** 2 + 1e-6))*2 - 1 # self.d_food goes from 0 to ~
self.s[2] = np.tanh((self.org_sens))*2 - 1
# print(self.s[0:3])
# Execute step of the Glauber algorithm to update the state of one unit
def GlauberStep(self, i=None):
'''
Utilizes: self.s, self.h, self.J
Modifies: self.s
'''
if i is None:
i = np.random.randint(self.size)
eDiff = 2 * self.s[i] * (self.h[i] + np.dot(self.J[i, :] + self.J[:, i], self.s))
#deltaE = E_f - E_i = -2 E_i = -2 * - SUM{J_ij*s_i*s_j}
#self.J[i, :] + self.J[:, i] are added because value in one of both halfs of J seperated by the diagonal is zero
if self.Beta * eDiff < np.log(1.0 / np.random.rand() - 1):
#transformed P = 1/(1+e^(deltaE* Beta)
self.s[i] = -self.s[i]
'''
# Execute step of the Glauber algorithm to update the state of one unit
# Faster version??
def GlauberStep(self, i=None):
#if i is None:
# i = np.random.randint(self.size) <-- commented out as not used
eDiff = np.multiply(np.multiply(2, self.s[i]), np.add(self.h[i], np.dot(np.add(self.J[i, :], self.J[:, i]), self.s)))
if np.multiply(self.Beta, eDiff) < np.log(1.0 / np.random.rand() - 1): # Glauber
self.s[i] = -self.s[i]
'''
# Execute time-step using an ANN algorithm to update the state of all units
def ANNStep(self):
# SIMPLE MLP
# TODO: add biases (add to GA as well)
af = lambda x: np.tanh(x) # activation function
Jhm = self.J + np.transpose(self.J) # connectivity for hidden/motor layers
Jh = Jhm[:, self.Ssize:-self.Msize] # inputs to hidden neurons
Jm = Jhm[:, -self.Msize:] # inputs to motor neurons
bh = self.h[self.Ssize:-self.Msize] # biases for hidden neurons
bm = self.h[-self.Msize:] # biases for motor neurons
# activate and update
new_h = af( self.Beta * ( np.dot(self.s, Jh) + bh ) )
self.s[self.Ssize:-self.Msize] = new_h
new_m = af( np.dot(self.s, Jm) + bm )
self.s[-self.Msize:] = new_m
# TODO: non-symmetric Jhm, need to change through to GA
# Compute energy difference between two states with a flip of spin i
def deltaE(self, i):
return 2 * (self.s[i] * self.h[i] + np.sum(
self.s[i] * (self.J[i, :] * self.s) + self.s[i] * (self.J[:, i] * self.s)))
# Update states of the agent from its sensors
def Update(self, settings, i=None):
if i is None:
i = np.random.randint(self.size)
if i == 0:
self.Move(settings)
self.UpdateSensors(settings)
elif i >= self.Ssize:
self.GlauberStep(i)
def SequentialUpdate(self, settings):
for i in np.random.permutation(self.size):
self.Update(settings, i)
def SequentialGlauberStepFastHelper(self, settings):
thermalTime = int(settings['thermalTime'])
self.UpdateSensors(settings)
self.s = SequentialGlauberStepFast(thermalTime, self.s, self.h, self.J, self.Beta, self.Ssize, self.size)
self.MoveOld(settings)
def ANNStepFastHelper(self, settings):
thermalTime = int(settings['thermalTime'])
self.UpdateSensors(settings)
self.s = ANNStepfast(thermalTime, self.s, self.h, self.J, self.Beta, self.Ssize, self.Msize)
self.MoveVelMotors(settings)
# Update all states of the system without restricted influences
def SequentialGlauberStep(self, settings):
thermalTime = int(settings['thermalTime'])
self.UpdateSensors(settings) # update sensors at beginning
# update all other neurons a bunch of times
for j in range(thermalTime):
perms = np.random.permutation(range(self.Ssize, self.size))
#going through all neuron exceot sensors in random permutations
for i in perms:
self.GlauberStep(i)
self.Move(settings) # move organism at end
# Update all states of the system without restricted influences
def ANNUpdate(self, settings):
thermalTime = int(settings['thermalTime'])
self.UpdateSensors(settings) # update sensors at beginning
# update all other neurons a bunch of times
for j in range(thermalTime):
self.ANNStep()
# self.Move(settings) # move organism at end
# self.MoveOld(settings)
self.MoveVelMotors(settings)
# update everything except sensors
def NoSensorGlauberStep(self):
perms = np.random.permutation(range(self.Ssize, self.size))
for i in perms:
self.GlauberStep(i)
# update sensors using glauber steps (dream)
def DreamSensorGlauberStep(self):
perms = np.random.permutation(self.size)
for i in perms:
self.GlauberStep(i)
# ensure that not all of the hidden neurons are connected to each other
def disconnect_hidden_neurons(self, settings):
numHNeurons = self.size - self.Ssize - self.Msize
perms = list(combinations(range(self.Ssize, self.Ssize + numHNeurons), 2))
numDisconnectedEdges = len(list(combinations(range(settings['numDisconnectedNeurons']), 2)))
for i in range(0, numDisconnectedEdges):
nrand = np.random.randint(len(perms))
iIndex = perms[nrand][0]
jIndex = perms[nrand][1]
self.J[iIndex,jIndex] = 0
# self.J[jIndex, iIndex] = 0
self.maskJ[iIndex, jIndex] = False
# self.maskJ[jIndex, iIndex] = False
# self.maskJtriu = np.triu(self.maskJ)
def assign_critical_values(self, settings):
# LOAD ISING CORRELATIONS
# filename = 'correlations-ising2D-size400.npy'
# Cdist = np.load(filename)
Cdist = settings['Cdist']
self.m1 = np.zeros(self.size)
self.C1 = np.zeros((self.size, self.size))
for ii in range(self.size):
for jj in range(max(ii + 1, self.Ssize), self.size):
ind = np.random.randint(len(Cdist))
self.C1[ii, jj] = Cdist[ind]
# re-sort the assigned correlations from the critical ising model so that their order matches the order of the
# actual correlations
def sort_critical_correlations(self):
c = self.C
x = np.arange(np.prod(c.shape)).reshape(c.shape)[self.maskJ] # index vector
c = c[self.maskJ]
c1 = self.C1[self.maskJ]
orderc = np.argsort(c)
orderc1 = np.argsort(c1)
C1_new = np.zeros((self.size, self.size))
# loop through index vector and re-sort assigned correlations to match order of actual correlations
# for iEdge, index in enumerate(x):
# i_index = int(np.floor(index / self.size))
# j_index = int(index % self.size)
#
# condition = np.subtract(orderc1, orderc[iEdge]) == 0
# # C1_index = int(np.extract(condition, orderc1))
# # C1_new[i_index, j_index] = c1[C1_index]
#
# C1_new[i_index, j_index] = c1[condition]
# # C1_new[i_index, j_index] = c1[orderc1[condition]]
for i, iEdge in enumerate(orderc):
index = x[iEdge]
i_index = int(np.floor(index / self.size))
j_index = int(index % self.size)
# condition = np.subtract(orderc1, orderc[i]) == 0
C1_new[i_index, j_index] = c1[orderc1[i]]
self.C1 = C1_new
# mutate the connectivity matrix of an organism by stochastically adding/removing an edge
def mutate(self, settings):
'''
Adds/removes a random edge depending on sparsity setting and randomly mutates another random edge
:param: settings
'''
# expected number of disconnected edges
numDisconnectedEdges = len(list(combinations(range(settings['numDisconnectedNeurons']), 2)))
totalPossibleEdges = len(list(combinations(range(self.size - self.Ssize - self.Msize), 2)))
# number of (dis)connected edges
connected = copy.deepcopy(self.maskJ)
disconnected = ~connected
np.fill_diagonal(disconnected, 0)
disconnected = np.triu(disconnected)
# keep sensors connected to hidden neurons
# TODO: allow the sensors to disconnect to some hidden neurons.
# Make sure minimum of 1 connection is made
connected[0:self.Ssize, :] = 0
connected[:, -self.Msize:] = 0
# things that need to be disconnected and not flagged to change
disconnected[0:self.Ssize, -self.Msize:] = 0
disconnected[0:self.Ssize, 0:self.Ssize] = 0
numEdges = np.sum(connected)
# positive value means too many edges, negative value means too little
edgeDiff = numEdges - (totalPossibleEdges - numDisconnectedEdges)
# edgeDiff = numEdges - numDisconnectedEdges
# TODO: investigate the empty connectivity matrix here
prob = sigmoid(edgeDiff) # probability near 1 means random edge will be removed, near 0 means random edge added
rand = np.random.rand()
if prob >= rand:
# remove random edge
i, j = np.nonzero(connected)
if len(i) > 0:
randindex = np.random.randint(0, len(i))
ii = i[randindex]
jj = j[randindex]
self.maskJ[ii, jj] = False
self.J[ii, jj] = 0
# TODO: is this a good way of making the code multi-purpose?
'''
try:
self.C1[ii, jj] = 0
except NameError:
pass
'''
else:
print('Connectivity Matrix Empty! Mutation Blocked.')
else:
# add random edge
i, j = np.nonzero(disconnected)
if len(i) > 0:
randindex = np.random.randint(0, len(i))
ii = i[randindex]
jj = j[randindex]
self.maskJ[ii, jj] = True
self.J[ii, jj] = np.random.uniform(-1, 1) * self.max_weights
# I.J[ii, jj] = np.random.uniform(np.min(I.J[I.Ssize:-I.Msize, I.Ssize:-I.Msize]) / 2,
# np.max(I.J[I.Ssize:-I.Msize, I.Ssize:-I.Msize]) * 2)
'''
try:
self.C1[ii, jj] = settings['Cdist'][np.random.randint(0, len(settings['Cdist']))]
except NameError:
pass
'''
else: # if connectivity matrix is full, just change an already existing edge
i, j = np.nonzero(connected)
randindex = np.random.randint(0, len(i))
ii = i[randindex]
jj = j[randindex]
# self.J[ii, jj] = np.random.uniform(-1, 1) * self.max_weights
# self.J[ii, jj] = np.clip(self.J[ii, jj] * np.random.normal(),
# -self.max_weights, self.max_weights)
self.J[ii, jj] = np.clip(self.J[ii, jj] + np.random.normal(loc=0, scale=settings['mutationSigma']),
-self.max_weights, self.max_weights)
# MUTATE RANDOM EDGE
i, j = np.nonzero(self.maskJ)
randindex = np.random.randint(0, len(i))
ii = i[randindex]
jj = j[randindex]
# self.J[ii, jj] = np.random.uniform(-1, 1) * self.max_weights
# self.J[ii, jj] = np.clip(self.J[ii, jj] * np.random.normal(),
# -self.max_weights, self.max_weights)
self.J[ii, jj] = np.clip(self.J[ii, jj] + np.random.normal(loc=0, scale=settings['mutationSigma']),
-self.max_weights, self.max_weights)
#Mutation of weights--> mutated weight is generated randomly from scratch
# MUTATE NEURON BIASES (local field h)
i = np.nonzero(self.maskh)[0]
randindex = np.random.randint(0, len(i))
ii = i[randindex]
self.h[ii] = np.random.uniform(-1, 1)
# MUTATE LOCAL TEMPERATURE
if settings['mutateB']:
deltaB = np.abs(np.random.normal(1, settings['sigB']))
self.Beta = self.Beta * deltaB #TODO mutate beta not by multiplying? How was Beta modified originally?
def add_neuron(self, settings):
# add a new disconnected neuron to the neural network
index = self.size - self.Msize # index to insert 0 in
# size
self.size += 1
# J, maskJ
self.J = self.insert_empty_row_col(self.J, index)
choices = np.arange(self.size)
choices = choices[choices!=index]
edge_index = np.random.choice(choices)
index_coord = np.sort([index, edge_index]) # sorting to place in upper triangle
self.J[index_coord[0], index_coord[1]] = np.random.uniform()*2 - 1
self.maskJ = self.insert_empty_row_col(self.maskJ, index)
self.maskJ[0:-self.Msize, -(self.Msize + 1)] = True
self.maskJ[-(self.Msize + 1), -(self.Msize + 1):] = True
# h, maskh
self.h = np.insert(self.h, index, 0)
self.maskh = np.insert(self.maskh, index, True)
self.randomize_state()
## TODO: there may be a few measurements that still need to update to the new size.
def rem_neuron(self, settings):
# remove a neuron from the neural network
index = np.random.randint(self.Ssize, self.size - self.Msize)
delmask = np.ones(self.J.shape, dtype='bool')
delmask[index, :] = False
delmask[:, index] = False
# J, maskJ
self.J = self.J[delmask]
self.maskJ = self.maskJ[delmask]
# h, maskh
self.h = np.delete(self.h, index)
self.maskh = np.delete(self.maskh, index)
# size
self.size -= 1
self.randomize_state()
def insert_empty_row_col(self, mat, index):
# new_size = mat.shape[0] + 1 # assuming square matrix
# new_mat = np.zeros((new_size, new_size))
#
# # top-left quadrant
# new_mat[:-(index + 1), :-(index + 1)] = mat[:-index, :-index]
# # bottom right quadrant
# new_mat[-index:, -index:] = mat[-index:, -index:]
# # bottom left quadrant
# new_mat[-index:, :-(index + 1)] = mat[-index:, :-index]
# # top right quadrant
# new_mat[:-(index + 1), -index] = mat[:-index:, -index]
if mat.dtype == 'bool':
new_mat = np.insert(mat, index, False, axis=0)
new_mat = np.insert(new_mat, index, False, axis=1)
elif mat.dtype == 'float64':
new_mat = np.insert(mat, index, 0, axis=0)
new_mat = np.insert(new_mat, index, 0, axis=1)
else:
print('Error inserting value in array! Wrong dtype!')
return new_mat
@jit(nopython=True)
def SequentialGlauberStepFast(thermalTime, s, h, J, Beta, Ssize, size):
all_neurons_except_sens = np.arange(Ssize, size)
#perms_list = np.array([np.random.permutation(np.arange(Ssize, size)) for j in range(thermalTime)])
random_vars = np.random.rand(thermalTime, len(all_neurons_except_sens)) #[np.random.rand() for i in perms]
for i in range(thermalTime):
#perms = perms_list[i]
#Prepare a matrix of random variables for later use
perms = np.random.permutation(np.arange(Ssize, size))
for j, perm in enumerate(perms):
rand = random_vars[i, j]
eDiff = 2 * s[perm] * (h[perm] + np.dot(J[perm, :] + J[:, perm], s))
#deltaE = E_f - E_i = -2 E_i = -2 * - SUM{J_ij*s_i*s_j}
#self.J[i, :] + self.J[:, i] are added because value in one of both halfs of J seperated by the diagonal is zero
if Beta * eDiff < np.log(1.0 / rand - 1):
#transformed P = 1/(1+e^(deltaE* Beta)
s[perm] = -s[perm]
return s
@jit(nopython=True)
def ANNStepfast(thermalTime, s, h, J, Beta, Ssize, Msize):
# SIMPLE MLP
# TODO: add biases (add to GA as well)
af = lambda x: np.tanh(x) # activation function
for i in range(thermalTime):
Jhm = J + np.transpose(J) # connectivity for hidden/motor layers
Jh = Jhm[:, Ssize:-Msize] # inputs to hidden neurons
Jm = Jhm[:, -Msize:] # inputs to motor neurons
bh = h[Ssize:-Msize] # biases for hidden neurons
bm = h[-Msize:] # biases for motor neurons
# activate and update
new_h = af(Beta * (np.dot(s, Jh) + bh))
s[Ssize:-Msize] = new_h
new_m = af(np.dot(s, Jm) + bm)
s[-Msize:] = new_m
return s
class food():
def __init__(self, settings):
self.xpos = uniform(settings['x_min'], settings['x_max'])
self.ypos = uniform(settings['y_min'], settings['y_max'])
self.energy = settings['food_energy']
def respawn(self, settings):
self.xpos = uniform(settings['x_min'], settings['x_max'])
self.ypos = uniform(settings['y_min'], settings['y_max'])
self.energy = settings['food_energy']
# ------------------------------------------------------------------------------+
# ------------------------------------------------------------------------------+
# --- FUNCTIONS ----------------------------------------------------------------+
# ------------------------------------------------------------------------------+
# ------------------------------------------------------------------------------+
def dist(x1, y1, x2, y2):
return sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def pdistance_pairwise(x0, x1, dimensions, food=False):
'''
Parameters
----------
x0, x1:
(vectorized) list of coordinates. Can be N-dimensional. e.g. x0 = [[0.5, 2.], [1.1, 3.8]].
dimensions:
size of the bounding box, array of length N. e.g. [8., 8.], [xmax - xmin, ymax - ymin].
food:
boolean signifying if the distance calculations are between organisms or between organisms and food. In the
latter case we don't need to compare it both ways around, in the former, theta_mat is a non-symmetric matrix.
Returns
-------
dist_mat:
upper triangle matrix of pairwise distances accounting for periodic boundaries
theta_mat:
full matrix of angles between each position accounting for periodic boundaries
'''
# get all unique pairs combinations
N1 = len(x0)
N2 = len(x1)
if food:
combo_index = list(product(np.arange(N1), np.arange(N2)))
else:
if not len(x0) == len(x1):
raise Exception('x0.shape[0] not equal to x1.shape[0] when comparing organisms.')
combo_index = list(combinations(np.arange(N1), 2))
Ii = np.array([x0[i[0]] for i in combo_index])
Ij = np.array([x1[i[1]] for i in combo_index])
# calculate distances accounting for periodic boundaries
# delta = np.abs(Ipostiled_seq - Ipostiled)
delta = Ij - Ii
delta = np.where(np.abs(delta) > 0.5 * dimensions, delta - np.sign(delta)*dimensions, delta)
dist_vec = np.sqrt((delta ** 2).sum(axis=-1))
theta_vec_ij = np.degrees(np.arctan2(delta[:, 1], delta[:, 0])) # from org i to org j
if not food:
theta_vec_ji = np.degrees(np.arctan2(-delta[:, 1], -delta[:, 0])) # from org j to org i
if food:
dist_mat = dist_vec.reshape(N1, N2)
else:
dist_mat = np.zeros((N1, N2))
theta_mat = np.zeros((N1, N2))
for ii, ind in enumerate(combo_index):
i = ind[0]
j = ind[1]
# can leave this as upper triangle since it's symmetric
if not food:
dist_mat[i, j] = dist_vec[ii]
# need to get a full matrix since eventually these angles are not symmetric
theta_mat[i, j] = theta_vec_ij[ii]
# if comparing org-to-org angles, need the other direction as well
if not food:
theta_mat[j, i] = theta_vec_ji[ii]
return dist_mat, theta_mat
def calc_heading(I, food):
d_x = food.xpos - I.xpos
d_y = food.ypos - I.ypos
theta_d = degrees(atan2(d_y, d_x)) - I.r
theta_d %= 360
# keep the angles between -180:180
if theta_d > 180:
theta_d -= 360
return theta_d
# Transform bool array into positive integer
def bool2int(x):
y = 0
for i, j in enumerate(np.array(x)[::-1]):
y += j * 2 ** i
return int(y)
# Transform positive integer into bit array
def bitfield(n, size):
x = [int(x) for x in bin(int(n))[2:]]
x = [0] * (size - len(x)) + x
return np.array(x)
def extract_plot_information(isings, foods):
isings_info = []
foods_info = []
for I in isings:
isings_info.append([I.xpos, I.ypos, I.r, I.energy])
for f in foods:
foods_info.append([f.xpos, f.ypos])
return isings_info, foods_info
def TimeEvolve(isings, foods, settings, folder, rep):
# if settings['energy_model']:
# for I in isings:
# I.energies = [] # Clear .energies, that .avg_energy is calculated from with each iteration
# I.energy = settings['initial_energy'] # Setting initial energy
for I in isings:
I.reset_state(settings)
I.generation = rep
T = settings['TimeSteps']
# for I in isings:
# I.position = np.zeros((2, T))
# Main simulation loop:
if settings['plot'] == True:
#plt.clf()
# plt.ion()
fig, ax = plt.subplots()
#fig.set_size_inches(15, 10)
isings_all_timesteps = []
foods_all_timesteps = []
#artists_all_TS = np.zeros(T)
#artist_list = []
'''
!!! iterating through timesteps
'''
if settings['parallel_computing'] and not settings['BoidOn'] and not settings['ANN']:
pool = mp.Pool(12)
for t in tqdm(range(T)):
for I in isings:
I.UpdateSensors(settings) # update sensors at beginning
vars_list = [(settings, I.Ssize, I.size, I.s, I.h, I.J, I.Beta) for I in isings]
s_list = pool.map(parallelizedSequGlauberStep, vars_list)