-
Notifications
You must be signed in to change notification settings - Fork 0
/
embodied_ising.py
2205 lines (1684 loc) · 81.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 compute_and_plot_heat_capacity_automatic
import animate
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
from shutil import copyfile
import automatic_plotting
from numba import jit
from numba import njit
import math
from os import listdir
from os.path import isfile, join
import subprocess
#import random
#from tqdm import tqdm
#from pympler import tracker
import visualize_in_model_natural_heat_capacity
import ray
import gzip
from speciation import speciation
from speciation import calculate_shared_fitness
from speciation import calculate_shared_fitness_continuous_species
# This is needed to initialize lowest energy network state, which is used for natural heat capacity calculations
from ising_net_fitness_landscape import all_states
from ising_net_fitness_landscape import calculate_energies
# ------------------------------------------------------------------------------+
# ------------------------------------------------------------------------------+
# --- CLASSES ------------------------------------------------------------------+
# ------------------------------------------------------------------------------+
# ------------------------------------------------------------------------------+
settings = {}
class ising:
# Initialize the network
def __init__(self, settings, netsize, Nsensors=2, Nmotors=2, name=None):
'''
For more attributes look at function reset_state, which is run at the start of every generation
More attributes are initialized there
'''
# 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) # TODO: is this bias, does this ever go over [0 0 0 0 0]???????
# 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.v_max = settings['v_max']
self.food_num_env = settings['food_num']
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
'''
initial beta
'''
if settings['diff_init_betas'] is None:
self.Beta = settings['init_beta']
else:
self.Beta = np.random.choice(settings['diff_init_betas'], 1)
#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.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 #currently median implemented
self.all_velocity = 0
self.avg_velocity = 0
self.v = 0.0
self.generation = 0
self.time_steps = 0 # time_steps of current generation
###Attributes required for heat capacity calculation###
# Those two vectors include the internal energy of the organism with different altered betas
self.cumulative_int_energy_vec = np.array([])
self.cumulative_int_energy_vec_quad = np.array([])
# This vector includes the factors that the vbeta value has been altered with
self.beta_vec = np.array([])
# This vector includes all heat capacity values of the organism with different altered beta values
self.heat_capacity_vec = np.array([])
self.selected = False # Those, that were selected in previous generation and copied into current get this
self.species = 0 # INT species name
self.isolated_population = 0 # INT Isolated population name
self.shared_fitness = 0 # Fitness calculated by speciation algorithm
self.prev_mutation = 'init' # Previous Mutation, can either be 'init', 'copy', 'point' or 'mate'
#self.assign_critical_values(settings) (attribute ising.C1)
if not settings['BoidOn']:
self.Update(settings, 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_v = np.random.rand() * self.v_max
self.s[2] = np.tanh(random_v)
# random_energy = np.random.rand() * self.food_num_env
# TODO: Make this more flexible!!
random_energy = np.random.rand() * 12
self.s[3] = np.tanh(random_energy)
def randomize_position(self, settings):
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
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 Move(self, settings):
# print(self.s[-2:])
# TODO: velocity coeffecient that can be mutated?
# UPDATE HEADING - Motor neuron s.[-self.Msize:self.Msize1]
self.r += (np.sum(self.s[-self.Msize:-self.Msize1]) / 2) * settings['dr_max'] * settings['dt']
self.r = self.r % 360
# UPDATE VELOCITY - Motor neuron s.[-self.Msize1:]
if settings['motor_neuron_acceleration']:
self.v += (np.sum(self.s[-self.Msize1:]) / 2) * settings['dv_max'] * settings['dt']
else:
v_new = (np.sum(self.s[-self.Msize1:]) / 2) * settings['v_max']
v_new_largest = v_new + settings['dv_max'] * settings['dt']
v_new_lowest = v_new - settings['dv_max'] * settings['dt']
if v_new > v_new_largest:
v_new = v_new_largest
if v_new < v_new_lowest:
v_new = v_new_lowest
self.v = v_new
if self.v < 0:
self.v = 0
if self.v > settings['v_max']:
self.v = settings['v_max']
if self.r > settings['r_max']:
self.r = settings['r_max']
if settings['energy_model']:
if self.energy >= (self.v * settings['cost_speed']) and self.v > settings['v_min']:
#if agend has enough energy and wants to go faster than min speed
self.energy -= self.v * settings['cost_speed']
elif self.v > settings['v_min']:
#if agned wants to go faster than min speed but does not have energy
self.v = settings['v_min']
self.all_velocity += self.v
# print('Velocity: ' + str(self.v) + str(self.s[-1]))
# 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
# torus boundary conditions
# if abs(self.xpos) > settings['x_max']:
# self.xpos = -self.xpos
#
# if abs(self.ypos) > settings['y_max']:
# self.ypos = -self.ypos
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 refers to the neuron state, which for sensor neurons is sensor input
# 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
self.s[2] = np.tanh(self.v)
self.s[3] = np.tanh(self.energy)
# TODO: define number of sensors here:
#settings['nSensors'] = 4
# 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
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
# activate and update
new_h = af(np.dot(self.s, Jh))
self.s[self.Ssize:-self.Msize] = new_h
new_m = af(np.dot(self.s, Jm))
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)
# Update all states of the system without restricted influences
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.Move(settings)
def SequentialGlauberStep(self, settings, thermal_time):
thermalTime = int(thermal_time)
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)
rand = np.random.rand()
GlauberStepFast(i, rand, self.s, self.h, self.J, self.Beta)
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
# 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):
# As permutation over complete network together with sensor neurons are taken, sensor neurons are thermalized as well
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)))
# settings['numDisconnectedNeurons'] how many hidden neurons are disconnenced fromeach other
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)
# mutate the connectivity matrix of an organism by stochastically adding/removing an edge
def mutate(self, settings):
'''
3 Mutations happening at once:
CONNECTIVITY Mutations:
One of these things happen
- A new edge is removed (according to sparsity settings more or less likely)
- or added (if no adding is possible some random edge gets new edge weight)
EDGE MUTATIONS
currently in an edge mutation means, that the whole edge weight is replaced by a randomly generated weight
BETA Mutations
Beta is mutated
'''
# ADDS/REMOVES RANDOM EDGE DEPENDING ON SPARSITY SETTING, RANDOMLY MUTATES ANOTHER RANDOM EDGE
# 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 #disconnected not connected
np.fill_diagonal(disconnected, 0)
disconnected = np.triu(disconnected)
# things that need to be connected and not flagged to change
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) #number of edges, that can actuall be disconnected (in beginning of simulatpn curr settings 3)
# 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) #for numDisconnectedNeurons=0 this means 0.5 --> equal probability of adding edge and removing edge # 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) #Indecies of neurons connected by edges that can be disconnected
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:
#looking for disconnected neurons that can be connected
# 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
#This only happens, when alogorithm tries to add edge, but everything is connected
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
# 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
#Mutation of weights--> mutated weight is generated randomly from scratch
# 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?
#TODO: ADDED POSIIBILITY OF RANDOM BETA TO GLOBALIZE SEARCH SPACE FOR BETA
if settings['beta_jump_mutations']:
if np.random.uniform(0, 1) < 0.1:
self.Beta = 10 ** np.random.uniform(-1, 1)
#biases GA pushing towards lower betas (artifical pressure to small betas)
# End of mutate (1)
def reset_state(self, settings):
# randomize internal state (not using self.random_state since it also randomizes sensors)
# TODO !!! THIS LINE SEEMS TO BE RESPONSIBLE FOR CHANGING HEAT CAPACITY PLOTS !!! This creats floats, when states are supposed to be ints!
# self.s = np.random.random(size=self.size) * 2 - 1
self.randomize_state()
# includes: #self.s = np.random.randint(0, 2, self.size) * 2 - 1
# 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
# cumulative internal energies, every entry in array represents cumulated int energies for one beta value
self.cumulative_int_energy_vec = np.array([])
self.cumulative_int_energy_vec_quad = np.array([])
self.beta_vec = np.array([])
self.all_recorded_inputs = [] # List of arrays For every time step the input value of every sensor is saved
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
#
# @jit(nopython=True)
# def SequentialGlauberStepFast(thermalTime, perms, random_vars, s, h, J, Beta):
# for j in range(thermalTime):
# for ind, i in enumerate(perms):
# rand = random_vars[ind]
# GlauberStepFast(i, rand, s, h, J, Beta)
#
# @jit(nopython=True)
# def GlauberStepFast(i, rand, s, h, J, Beta ):
# '''
# Utilizes: self.s, self.h, self.J
# Modifies: self.s
# '''
#
# eDiff = 2 * s[i] * (h[i] + np.dot(J[i, :] + J[:, i], 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[i] = -s[i] # TODO return s!!!!!!!
# @jit(nopython=True)
# def SequentialGlauberStepFast(thermalTime, perms_list, random_vars_list, s, h, J, Beta):
# for j in range(thermalTime):
# perms = perms_list[j]
# random_vars = random_vars_list[j]
# for ind, i in enumerate(perms):
# rand = random_vars[ind]
# eDiff = 2 * s[i] * (h[i] + np.dot(J[i, :] + J[:, i], 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[i] = -s[i]
# return s
@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
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 save_whole_project(folder):
'''Copies complete code into simulation folder'''
cwd = os.getcwd()
onlyfiles = [f for f in listdir(cwd) if isfile(join(cwd, f))]
save_folder = folder + 'code/'
for file in onlyfiles:
save_code(save_folder, file)
def save_code(folder, filename):
src = filename
dst = folder + src
copyfile(src, dst)
def dist(x1, y1, x2, y2):
return sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
#@jit(nopython=True)
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, settings):
isings_info = []
foods_info = []
for I in isings:
if settings['energy_model']:
isings_info.append([I.xpos, I.ypos, I.r, I.energy, I.isolated_population, I.species])
else:
isings_info.append([I.xpos, I.ypos, I.r, I.fitness, I.isolated_population, I.species])
for f in foods:
foods_info.append([f.xpos, f.ypos])
return isings_info, foods_info
def TimeEvolve(isings, foods, settings, folder, rep, total_timesteps, nat_heat_gens, beta_facs, calc_heat_cap_boo,
record, save_energies_velocities):
[ising.reset_state(settings) for ising in isings]
if settings['random_time_steps_power_law']:
low_limit, high_limit, a = settings['random_time_steps_power_law_limits']
T = int((1-np.random.power(a))*high_limit + low_limit)
elif settings['random_time_steps']:
random_ts_limits = settings['random_time_step_limits']
T = np.random.randint(random_ts_limits[0], random_ts_limits[1])
else:
T = settings['TimeSteps']
for I in isings:
I.time_steps = T
for I in isings:
I.position = np.zeros((2, T))
# Main simulation loop:
if settings['plot'] == True:
fig, ax = plt.subplots()
#fig.set_size_inches(15, 10)
isings_all_timesteps = []
foods_all_timesteps = []
# This switches on natural heat capacity calculations
'''
!!! iterating through timesteps
'''
#for t in tqdm(range(T)):
for t in range(T):
#TODO: Is it good to randomize neuron states each time step? (Not done before)
#[I.randomize_state() for I in isings]
#print(len(foods))
# print('\r', 'Iteration {0} of {1}'.format(t, T), end='') #, end='\r'
# print('\r', 'Tstep {0}/{1}'.format(t, T), end='') # , end='\r'
if not (settings['chg_food_gen'] is None):
if t == settings['chg_food_gen'][0]:
settings['num_food'] = settings['chg_food_gen'][1]
if settings['seasons'] == True:
foods = seasons(settings, foods, t, T, total_timesteps)
# PLOT SIMULATION FRAME
if settings['plot'] == True and (t % settings['frameRate']) == 0:
#plot_frame(settings, folder, fig, ax, isings, foods, t, rep)
isings_info, foods_info = extract_plot_information(isings, foods, settings)
isings_all_timesteps.append(isings_info)
foods_all_timesteps.append(foods_info)
interact(settings, isings, foods)
if save_energies_velocities:
for I in isings:
I.velocities.append(I.v)
if record:
num_sensors = settings['nSensors']
for I in isings:
all_recorded_inputs = I.all_recorded_inputs
# TODO: does this work as intended?:
recorded_input = I.s[:num_sensors]
all_recorded_inputs.append(recorded_input)
I.all_recorded_inputs = all_recorded_inputs
# Before normal thermalization, prepare_natural_heat_capacity does dream-state thermalization with different
# beta values and calculates heat-capacity
if calc_heat_cap_boo:
prepare_natural_heat_capacity(settings, isings, beta_facs)
if settings['BoidOn']:
boid_update(isings, settings)
for I in isings:
I.position[:, t] = [I.xpos, I.ypos]
else:
#parallelization here
if settings['ANN']:
I.ANNUpdate(settings)
else:
if settings['parallel_computing']:
# parallelizedSequGlauberSteps(isings, settings)
ray.init(num_cpus=settings['cores'])
ray_funcs = [ray_parallel_Glauber_steps.remote(I, settings) for I in isings]
ray.get(ray_funcs)
else:
[I.SequentialGlauberStepFastHelper(settings) for I in isings]
if calc_heat_cap_boo:
calculate_natural_heat_capacity(isings, T, beta_facs)
#try:
# except Exception:
# print('Could not create plots for natural heat capacity for generation {}'.format(rep))
if settings['plot']:
#plotting.animate_plot(artist_list, settings, ax, fig)
# try:
# if settings['fading_traces_animation']:
animate.animate_plot_Func(isings_all_timesteps, foods_all_timesteps, settings, ax, fig, rep, t, folder)
# else:
# plotting.animate_plot_Func(isings_all_timesteps, foods_all_timesteps, settings, ax, fig, rep, t, folder)
# except Exception:
# print('There occurred an error during animation...the simulation keeps going')
'''
for I in isings:
if settings['ANN']:
I.ANNUpdate(settings)
else:
I.SequentialGlauberStep(settings)
I.position[:, t] = [I.xpos, I.ypos]
'''
'''
#Helper functions parallelization
def parallelSequGlauberStep(I, settings):
# I = copy.deepcopy(I)
I.SequentialGlauberStep()
return I
'''