-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostProcessor.py
261 lines (217 loc) · 9.47 KB
/
PostProcessor.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
#############################################
## The PostProcessor class for the ##
## nest transfer experiment suimulations ##
## allows to create visual representations ##
## of the simulation results ##
## (c) Artem Pashchinskiy, UCLA, 2019 ##
#############################################
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
import os
import csv
import glob
import shutil
import misc
from statistics import mean, stdev
from math import sqrt
import time
class PostProcessor:
# this constructor expects an AntSim instance to be passed as parent
def __init__(self, parent, name = None):
self.parentSim = parent
self.timestamp = self.parentSim.getID()
self.num_sets = 0
self.first_crossing_data = list()
self.last_crossing_data = list()
self.num_crossings = list()
self.final_num = list()
if name == None:
self.foldername = 'results/{}'.format(self.timestamp)
else:
self.foldername = 'results/{}/{}'.format(name[0], name[1])
if not os.path.exists(self.foldername):
os.makedirs(self.foldername)
self.first_crossing_fig, self.fca = plt.subplots(1, 1)
self.first_crossing_fig.suptitle('First crossing time')
self.fca.set_ylim(0, self.parentSim.pars['ITER'])
self.last_crossing_fig, self.lca = plt.subplots(1, 1)
self.last_crossing_fig.suptitle('Last crossing time')
self.lca.set_ylim(0, self.parentSim.pars['ITER'])
self.num_crossings_fig, self.nca = plt.subplots(1, 1)
self.num_crossings_fig.suptitle('Nest transfer crossings count')
self.final_num_fig, self.fna = plt.subplots(1, 1)
self.final_num_fig.suptitle('Final number of ants on the cooler side')
self.fna.set_ylim(0, self.parentSim.pars['NUM'])
def add_subplot(self, fig):
if self.num_sets == 0:
return fig.axes[0]
else:
n = len(fig.axes)
for i in range(n):
fig.axes[i].change_geometry(1, n+1, i+1)
ax = fig.add_subplot(1, n+1, n+1)
return ax
### Creates subplots with a variety of relocation statistics
## (*) Ran in the "one" mode, it produces plots based on a single simulation run
## (*) If want to aggreagate data form multiple runs into a single plot, first
## call nest_transfer in the "add" mode after each run and then call the "process" and "save"
## (*) If want to to aggreagate data form multiple groups of runs (i.e. tets set of 3 parameter values with 5 runs per value),
## call "add" after each run, "process" after each group of runs (i.e. when all trials uner the same parameter value are coimpleted)
## and "save" after all groups of parameters are processed
def nest_transfer(self, nest_transfer_data, mode = 'one', name = "test", numtrials = 1):
trials_name = [name]
left = nest_transfer_data[:, :2]
right = nest_transfer_data[:, 2:]
if mode == 'one':
plt.close()
plt.plot(left[:, 0],left[:, 1],'r') # plotting t,a separately
plt.plot(right[:, 0], right[:, 1],'b') # plotting t,b separately
plt.savefig(self.foldername + "/nest_transfer_fig.png")
plt.close()
elif mode == 'add':
crossings = np.where(left[:, 1]==right[:, 1])[0]
crossings_counter = 0
crossings2 = np.append([0], crossings)
for i in range(1, crossings2.size):
if crossings2[i] - crossings2[i-1] > 1:
crossings_counter += 1
if crossings.size == 0:
crossings = [left[:, 0][-1]]
self.first_crossing_data.append(crossings[0])
self.last_crossing_data.append(crossings[-1])
self.final_num.append(left[:, 1][-1])
self.num_crossings.append(crossings_counter)
elif mode == 'process':
ax = self.add_subplot(self.num_crossings_fig)
ax.boxplot(self.num_crossings, labels = trials_name)
with open (self.foldername+"/crossings_count_file.csv", 'a') as ncf:
ncf.write(trials_name[0]+",")
ncf.write(get_writable_data(self.num_crossings, numtrials))
ax = self.add_subplot(self.first_crossing_fig)
ax.set_ylim(0, self.parentSim.pars['ITER'])
ax.boxplot(self.first_crossing_data, labels = trials_name)
with open (self.foldername+"/first_crossing_file.csv", 'a') as fcf:
fcf.write(trials_name[0]+",")
fcf.write(get_writable_data(self.first_crossing_data, numtrials))
ax = self.add_subplot(self.last_crossing_fig)
ax.set_ylim(0, self.parentSim.pars['ITER'])
ax.boxplot(self.last_crossing_data, labels = trials_name)
with open (self.foldername+"/last_crossing_file.csv", 'a') as lcf:
lcf.write(trials_name[0]+",")
lcf.write(get_writable_data(self.last_crossing_data, numtrials))
ax = self.add_subplot(self.final_num_fig)
ax.set_ylim(0, self.parentSim.pars['NUM'])
ax.boxplot(self.final_num, labels = trials_name)
with open (self.foldername+"/final_number_file.csv", 'a') as fnf:
fnf.write(trials_name[0]+",")
fnf.write(get_writable_data(self.final_num, numtrials))
#tm = time.time()
self.parameters_dump(self.parentSim.pars, trials_name[0])
#tM = time.time()
#print("Par dump = "+str(tM - tm)+" seconds")
#tm = time.time()
self.relocate_traj(self.foldername, trials_name[0])
#tM = time.time()
#print("Rel traj = "+str(tM - tm)+" seconds")
#tm = time.time()
misc.bulk_center_mass(self.foldername, trials_name[0], self.parentSim.pars['ITER'], self.parentSim.arena.minX, self.parentSim.arena.maxX)
#tM = time.time()
#print("BCM = "+str(tM - tm)+" seconds")
self.parentSim.runcount = 0
self.num_sets += 1
elif mode == 'save':
np.save(self.foldername + "/num_crossings.npy", self.num_crossings)
np.save(self.foldername + "/first_cross.npy", self.first_crossing_data)
np.save(self.foldername + "/last_cross.npy", self.last_crossing_data)
np.save(self.foldername + "/final_num.npy", self.final_num)
self.num_crossings_fig.savefig(self.foldername + "/num_crossings.png")
self.first_crossing_fig.savefig(self.foldername + "/first_cross.png")
self.last_crossing_fig.savefig(self.foldername + "/last_cross.png")
self.final_num_fig.savefig(self.foldername + "/final_num.png")
plt.close()
### plot density of either interactions or trajectorjes (depending on mode)
def plot2dkernel(self, interactions_data = None, mode = 'inter'):
# get raw data
if mode == "inter":
x = np.array(interactions_data[0])
y = np.array(interactions_data[1])
elif mode == "traj":
x = np.zeros(1)
y = np.zeros(1)
for f in glob.glob(self.foldername + "/trajectories*.csv"):
x_f = np.genfromtxt(f, usecols = (2), dtype = int, delimiter = ',')
y_f = np.genfromtxt(f, usecols = (3), dtype = int, delimiter = ',')
x = np.hstack((x, x_f))
y = np.hstack((y, y_f))
x = x[1:]
y = y[1:]
xmin, xmax = 0, self.parentSim.arena.dimX
ymin, ymax = 0, self.parentSim.arena.dimY
# Peform the kernel density estimate
xx, yy = np.mgrid[xmin:xmax:50j, ymin:ymax:50j]
positions = np.vstack([xx.ravel(), yy.ravel()])
values = np.vstack([x, y])
kernel = st.gaussian_kde(values)
kernel.set_bandwidth(0.15)
f = np.reshape(kernel(positions).T, xx.shape)
fig = plt.figure()
ax = fig.gca()
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
# Contourf plot
cfset = ax.contourf(xx, yy, f, cmap='Blues', alpha=0.9)
## Or kernel density estimate plot instead of the contourf plot
#ax.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax])
# Contour plot
cset = ax.contour(xx, yy, f, colors='k')
# add background image of the arena/field
arenaIm = plt.imread(self.parentSim.arena.arFile.replace(".npy", ".gif"))
ax.imshow(arenaIm)
# making plots looks pretty
ax.invert_yaxis()
ax.set_yticklabels([])
ax.set_xticklabels([])
if mode == 'inter':
plt.title("Interactctions kernel density estimation")
plt.savefig(self.foldername + "/interactions_kernel_density_{}.png".format(self.parentSim.runcount))
interactions_data2 = np.transpose(np.array(interactions_data))
np.savetxt(self.foldername + "/interactions_{}.csv".format(self.parentSim.runcount), interactions_data2, delimiter = ',', fmt = '%s')
elif mode == 'traj':
plt.title("Trajectories kernel density estimation")
plt.savefig(self.foldername + "/traj_kernel_density_{}.png".format(self.parentSim.runcount))
plt.close()
# plot where interactions are hapenning (as individual dots)
def simple_interactions(self, interactions_data, mode = 'run'):
plt.figure("simple_interactions")
plt.imshow(plt.imread(self.parentSim.arena.arFile.split('.')[0]+".gif"))
plt.scatter(interactions_data[0], interactions_data[1], c = 'Red', alpha = 0.3)
plt.savefig(self.foldername + "/simple_interactions{}.png".format(self.parentSim.runcount))
plt.close()
# log the parameter set used to run the specific simulation group
def parameters_dump(self, pars_dict, name = ''):
with open(self.foldername + "/" + name + "_pars.csv", "w") as csvfile:
w = csv.writer(csvfile)
for key, val in pars_dict.items():
w.writerow([key, val])
# move trajectories files to the folder with a specified trial name (housekeeping)
def relocate_traj(self, foldername, name):
newfolder = '{}/{}'.format(foldername, name)
if not os.path.exists(newfolder):
os.makedirs(newfolder)
for f in glob.glob('{}/trajectories*.csv'.format(foldername)):
shutil.move(f, newfolder)
# compute mean, stddev, and stderr of the data and return it in the string
def get_writable_data(data, numtrials):
mean_str = str(mean(data))[:8]
try:
stdev_str = str(stdev(data))[:8]
stdev_num = stdev(data)
#if not enough data to compute stdev
except statistics.StatisticsError:
stdev_str = '0'
stdev_num = 0
stderr_str = str(stdev_num/sqrt(numtrials))[:8]
return(mean_str + ',' + stdev_str + ',' + stderr_str + '\n')