-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_agent_based.py
113 lines (85 loc) · 3.44 KB
/
run_agent_based.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
from datetime import datetime
import yaml
import os
import time
import numpy as np
import matplotlib.pylab as plt
from generate_data import create_knapsack_data, create_knapsack_correlated
from mabea.lattice import Lattice
def log_genotype(latt, timestamp, it):
genotypes = []
for agent in latt.grid:
genotypes.append((agent.genotype.tolist(), agent.fitness))
with open(os.path.join('results', timestamp, f'genotypes_{it}.json'), 'w') as f:
for genotype in genotypes:
f.write(f"{genotype[0]}, {genotype[1]} \n")
def run(config, profits, weights, capacity):
np.random.seed(config['exp_seed'])
latt = Lattice(profits, weights, capacity, size=config['lattice_size'])
means = []
maxes = []
rsc_mean = []
rsc_std = []
diversities = []
es_it = 0
prev_maximum = 0
start = time.time()
for i in range(config['n_generations']):
latt.selection()
latt.mutation(profits, weights, capacity, mutation_probability=config['mutation_probability'])
if config['print_interval'] is not None:
if i % config['print_interval'] == 0:
os.system('clear')
print(i)
latt.print()
if config['log_genotypes']:
log_genotype(latt, timestamp, i)
if config['log_diversity']:
diversities.append((i, latt.diversity()))
means.append(np.mean(latt.get_energies_lattice()))
maximum = np.amax(latt.get_energies_lattice())
maxes.append(maximum)
rsc_mean.append(np.mean(latt.get_resources()))
rsc_std.append(np.mean(latt.get_resources()))
if maximum <= prev_maximum:
es_it += 1
else:
prev_maximum = maximum
es_it = 0
if es_it == config['early_stopping']:
break
print(f'Duration: {time.time() - start}')
# Remember the resutls
print(f'Best result: {np.amax(maxes)}')
return means, maxes, rsc_mean, rsc_std, diversities, latt
if __name__ == '__main__':
timestamp = datetime.now().strftime("%d-%b-%Y-%H-%M-%S")
os.makedirs(os.path.join('results', timestamp))
with open('config.yml') as f:
config = yaml.load(f, Loader=yaml.FullLoader)
np.random.seed(config['data_seed'])
if config['dataset'] == 'random':
profits, weights, capacity = create_knapsack_data(item_count=config['item_count'])
elif config['dataset'] == 'correlated':
profits, weights, capacity = create_knapsack_correlated(item_count=config['item_count'])
else:
raise ValueError("Config param 'dataset' can be 'random' or 'correlated'")
means, maxes, rsc_mean, rsc_std, diversities, latt = run(config, profits, weights, capacity)
plt.figure()
plt.title('Fitness')
plt.plot(means)
plt.plot(maxes, 'r')
plt.legend(['mean', 'max'])
plt.savefig(os.path.join('results', timestamp, 'fitness.png'))
plt.figure()
plt.title('Available resources')
plt.plot(rsc_mean)
plt.plot(rsc_std, 'r')
plt.savefig(os.path.join('results', timestamp, 'resources.png'))
plt.figure()
plt.title('Diversity during experiment')
plt.plot([d[0] for d in diversities], [d[1] for d in diversities])
plt.savefig(os.path.join('results', timestamp, 'diversity.png'))
log_genotype(latt, timestamp, it='final')
with open(os.path.join('results', timestamp, 'config.yml'), 'w') as f:
f.write(yaml.dump(config))