createPlots.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 '''
4 Copyright (c) 2016, Braun Kai, Gehrung Joachim, Heizmann Heinrich, Meissner Pascal
5 All rights reserved.
6 
7 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
8 
9 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
10 
11 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
12 
13 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
14 
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16 '''
17 
18 import csv
19 import numpy as np
20 import matplotlib.pyplot as plt
21 
22 # Used for increasing all values less than the given value to make them visible on the bar chart.
23 thresholdForValueIncreasing = 0.1
24 thresholdForValueIncreasingStandalone = 0.001
25 thresholdForValueIncreasingStandaloneLog = 0.00001
26 
27 # Define colors for bar segments.
28 # For colors see here: http://micropore.wordpress.com/2012/05/16/python-html-colors/
29 #colors = ['#b167ce','#77cfbe','#9e79cd','#80d6a4','#9785d6','#8fd3a6']
30 colors = ['Salmon','Khaki','GreenYellow','Aquamarine','Thistle','Moccasin']
31 
32 def generateRuntimePlot(pathToCsv, pathToImage, meanOverTurns, xtics, textoffsetX, textoffsetY):
33 
34  maxSamples = 4
35  maxSceneobjects = 6
36  samplesPerKernel = 100
37 
38  #************************************#
39  # Preprocess values.
40  #************************************#
41 
42  # Iterate over all ISM experiments and calculate its runtime.
43  psmScore = []
44  for samples in range(1, maxSamples + 1):
45  for sceneobjects in range(0, maxSceneobjects):
46  experiment = str(samples * samplesPerKernel) + '_' + str(sceneobjects).zfill(2)
47  pathExperimentCsv = pathToCsv + '/' + experiment + '/' + experiment + '.csv'
48 
49  # Get the number of evaluation turns from the number of samples.
50  numberOfTurns = sum(1 for row in csv.reader(open(pathExperimentCsv, 'rb'), delimiter=','))
51 
52  if meanOverTurns:
53  numberOfTurns /= (sceneobjects + 1)
54  print 'Evaluating experiment ' + experiment + '. Number of turns is ' + str(numberOfTurns) + '.'
55  else:
56  print 'Evaluating experiment ' + experiment + '.'
57 
58  # Open experiment file and calculate the mean runtime.
59  with open(pathExperimentCsv, 'rb') as csvfile:
60  reader = csv.reader(csvfile, delimiter=',')
61 
62  # Skip csv header.
63  reader.next()
64 
65  score = []
66  # Sum over all samples of a turn, then add it to the score list.
67  for turn in range(0, numberOfTurns - 1):
68  turnScore = 0.0;
69 
70  if meanOverTurns:
71  for i in range(0, sceneobjects):
72  turnScore += float(reader.next()[1])
73  turnScore /= (sceneobjects + 1)
74  else:
75  turnScore += float(reader.next()[6])
76 
77  score.append(turnScore)
78 
79  # Calculate the runtime as mean of the score list.
80  # Skip the first six entries because they were calculated for an insufficient number of evidences.
81  if meanOverTurns:
82  psmScore.append(np.array(score[6:]).mean())
83  else:
84  psmScore.append(np.array(score).mean())
85 
86  #************************************#
87  # Convert data in plottable format.
88  #************************************#
89 
90  # Create yLabels
91  yLabels = []
92  for samples in range(1, maxSamples + 1):
93  yLabels.append(samples * samplesPerKernel)
94 
95  # Build data and labels.
96  data = np.zeros((maxSceneobjects, maxSamples))
97  labels = np.zeros((maxSamples, maxSceneobjects))
98  for x in range(0, maxSamples):
99  for y in range(0, maxSceneobjects):
100  value = psmScore[x * (maxSceneobjects) + y]
101 
102  # Set label
103  labels[x][y] = value
104 
105  # Every value to small to be visualized is set to a given threshold value.
106  #if value < thresholdForValueIncreasing:
107  #data[y][x] = thresholdForValueIncreasing
108  #else:
109  #data[y][x] = value
110  data[y][x] = value
111 
112  #************************************#
113  # Plot stacked bar diagram.
114  #************************************#
115 
116  # Build indices for position on y-axis.
117  y_pos = np.arange(len(yLabels))
118 
119  # Prepare figure
120  fig = plt.figure(figsize=(10,4))
121  ax = fig.add_subplot(111)
122 
123  # Generate patches for each bar.
124  patch_handles = []
125  left = np.zeros(len(yLabels))
126  for i, d in enumerate(data):
127  patch_handles.append(ax.barh(y_pos, d, color=colors[i % len(colors)], align='center', label='%i' % (i + 1), left=left))
128  left += d
129 
130  # Annotate each bar segment with the given label.
131  for j in xrange(len(patch_handles)):
132  for i, patch in enumerate(patch_handles[j].get_children()):
133  bl = patch.get_xy()
134 
135  # Set text position.
136  x = 0.5 * patch.get_width() + bl[0] + textoffsetX
137  y = 0.5 * patch.get_height() + bl[1] + textoffsetY
138 
139  # Print text, if there's enough space
140  if meanOverTurns:
141  if labels[i,j] > 110:
142  ax.text(x,y, "%10.2f" % (labels[i,j]), ha='center', fontweight='bold', fontsize=15)
143  else:
144  if labels[i,j] > 1.5:
145  ax.text(x,y, "%10.2f" % (labels[i,j]), ha='center', fontweight='bold', fontsize=15)
146 
147  # Configure axes and plot.
148  ax.set_yticks(y_pos)
149  ax.set_yticklabels(yLabels)
150 
151  ax.xaxis.grid()
152 
153  ax.set_xlabel('Laufzeit in Millisekunden', fontweight='bold')
154  ax.set_ylabel('Datenpunkte pro Trajektorie', fontweight='bold')
155  ax.invert_yaxis()
156 
157  ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.08), ncol=6, fancybox=True, shadow=True)
158 
159  plt.xlim([0,xtics])
160  #plt.show()
161  plt.savefig(pathToImage)
162 
163 def generateRuntimePlotStandalone(pathToCsv, pathToImage, maxSceneobjects, useLog, textoffsetX, textoffsetY):
164 
165  #************************************#
166  # Preprocess values.
167  #************************************#
168 
169  # Iterate over all ISM experiments and calculate its runtime.
170  psmScore = []
171  for obj in range(1, maxSceneobjects + 1):
172  for evidence in range(1, maxSceneobjects + 1):
173  pathExperimentCsv = pathToCsv + '/obj_' + str(obj) + '_run_' + str(evidence) + '/run_' + str(obj) + '.csv'
174 
175  print 'Evaluating ' + str(obj) + ' object(s) with ' + str(evidence) + ' evidences.'
176 
177  # Get the number of evaluation turns from the number of samples.
178  numberOfTurns = sum(1 for row in csv.reader(open(pathExperimentCsv, 'rb'), delimiter=','))
179  numberOfTurns /= (maxSceneobjects + 1)
180 
181  # Open experiment file and calculate the mean runtime.
182  with open(pathExperimentCsv, 'rb') as csvfile:
183  reader = csv.reader(csvfile, delimiter=',')
184 
185  # Skip csv header.
186  reader.next()
187 
188  score = []
189  # Sum over all samples of a turn, then add it to the score list.
190  for turn in range(0, numberOfTurns - 1):
191  turnScore = 0.0;
192 
193  for i in range(0, obj):
194  turnScore += float(reader.next()[1])
195 
196  score.append(turnScore / obj)
197 
198  # Calculate the runtime as mean of the score list.
199  # Skip the first six entries because they were calculated for an insufficient number of evidences.
200  psmScore.append(np.array(score[6:]).mean())
201 
202  #************************************#
203  # Convert data in plottable format.
204  #************************************#
205 
206  # Create yLabels
207  yLabels = []
208  for samples in range(1, maxSceneobjects + 1):
209  yLabels.append(samples)
210 
211  # Build data and labels.
212  data = np.zeros((maxSceneobjects, maxSceneobjects))
213  labels = np.zeros((maxSceneobjects, maxSceneobjects))
214  for x in range(0, maxSceneobjects):
215  for y in range(0, maxSceneobjects):
216  value = psmScore[x * (maxSceneobjects) + y]
217 
218  # Set label
219  labels[x][y] = value
220 
221  # Every value to small to be visualized is set to a given threshold value.
222  if useLog:
223  #if value < thresholdForValueIncreasingStandaloneLog:
224  #data[y][x] = thresholdForValueIncreasingStandaloneLog
225  #else:
226  #data[y][x] = value
227  data[y][x] = value
228  else:
229  #if value < thresholdForValueIncreasingStandalone:
230  #data[y][x] = thresholdForValueIncreasingStandalone
231  #else:
232  #data[y][x] = value
233  data[y][x] = value
234 
235  #************************************#
236  # Plot stacked bar diagram.
237  #************************************#
238 
239  # Build indices for position on y-axis.
240  y_pos = np.arange(len(yLabels))
241 
242  # Prepare figure
243  fig = plt.figure(figsize=(10,4))
244  ax = fig.add_subplot(111)
245 
246  # Generate patches for each bar.
247  patch_handles = []
248  left = np.zeros(len(yLabels))
249  for i, d in enumerate(data):
250  patch_handles.append(ax.barh(y_pos, d, color=colors[i % len(colors)], align='center', label='%i' % (i + 1), left=left))
251  left += d
252 
253  # Annotate each bar segment with the given label.
254  for j in xrange(len(patch_handles)):
255  for i, patch in enumerate(patch_handles[j].get_children()):
256  bl = patch.get_xy()
257 
258  # Set text position.
259  x = 0.5 * patch.get_width() + bl[0] + textoffsetX
260  y = 0.5 * patch.get_height() + bl[1] + textoffsetY
261 
262  # Print text, if there's enough space
263  if labels[i,j] > 5:
264  ax.text(x,y, "%10.2f" % (labels[i,j]), ha='center', va='center', fontweight='bold', fontsize=15)
265 
266  # Configure axes and plot.
267  ax.set_yticks(y_pos)
268  ax.set_yticklabels(yLabels)
269 
270  ax.xaxis.grid()
271 
272  ax.set_xlabel('Laufzeit in Millisekunden', fontweight='bold')
273  ax.set_ylabel('Objekte pro Szene', fontweight='bold')
274  ax.invert_yaxis()
275 
276  ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.08), ncol=6, fancybox=True, shadow=True)
277 
278  # Set x-axis to logarithmic
279  if useLog:
280  ax.set_xscale('log')
281 
282  plt.xlim([0,40])
283  #plt.show()
284  plt.savefig(pathToImage)
285 
286 def generateRuntimePlotKickass(pathToCsv, pathToImage, maxSceneobjects, useLog, meanOverTurns):
287 
288  #************************************#
289  # Preprocess values.
290  #************************************#
291 
292  # Iterate over all ISM experiments and calculate its runtime.
293  psmScore = []
294  for obj in range(1, maxSceneobjects + 1):
295  sceneId = 'run_' + str(obj).zfill(2)
296  pathExperimentCsv = pathToCsv + '/' + sceneId + '/' + sceneId + '.csv'
297 
298  print 'Evaluating ' + str(obj) + ' object(s) with ' + str(obj) + ' evidences.'
299 
300  # Get the number of evaluation turns from the number of samples.
301  numberOfTurns = sum(1 for row in csv.reader(open(pathExperimentCsv, 'rb'), delimiter=','))
302 
303  if meanOverTurns:
304  numberOfTurns /= obj
305 
306  # Open experiment file and calculate the mean runtime.
307  reader = csv.reader(open(pathExperimentCsv, 'rb'), delimiter=',')
308 
309  # Skip csv header.
310  reader.next()
311 
312  score = []
313  # Sum over all samples of a turn, then add it to the score list.
314  for turn in range(0, numberOfTurns - 1):
315  turnScore = 0.0;
316 
317  if meanOverTurns:
318  for i in range(0, obj):
319  turnScore += float(reader.next()[1])
320  turnScore /= obj
321  else:
322  turnScore += float(reader.next()[6])
323 
324  score.append(turnScore)
325 
326  # Calculate the runtime as mean of the score list.
327  # Skip the first six entries because they were calculated for an insufficient number of evidences.
328  if meanOverTurns:
329  objScore = np.array(score[6:]).mean() / 1000
330  else:
331  objScore = np.array(score).mean() / 1000
332 
333  #if objScore == 0.0: objScore = 1.0
334  #print str(obj) + ": " + str(objScore)
335  psmScore.append(objScore)
336 
337  #************************************#
338  # Plot line diagram.
339  #************************************#
340 
341  # Create data for x- and y-axis
342  xData = np.arange(1.0, maxSceneobjects + 1, 1.0)
343  yData = np.array(psmScore)
344 
345  # Prepare figure
346  fig = plt.figure(figsize=(10,4))
347  ax = fig.add_subplot(111)
348 
349  ax.xaxis.grid()
350 
351  ax.set_xlabel('Objekte pro Szene', fontweight='bold')
352  ax.set_ylabel('Laufzeit in Sekunden', fontweight='bold')
353 
354  ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.08), ncol=6, fancybox=True, shadow=True)
355 
356  # Set x-axis to logarithmic
357  if useLog:
358  ax.set_yscale('log')
359 
360  ax.plot(xData, yData, 'ro-')
361 
362  #plt.show()
363  plt.savefig(pathToImage)
364 
365 def main():
366 
367  # Path to the directory containing the results of the experiments.
368  pathToExperiments = '/home/joachim/Schreibtisch/Evaluation/Laufzeitmessung'
369 
370  # Generate runtime bar plots.
371  #generateRuntimePlot(pathToExperiments + '/simple/runtime/PSM', pathToExperiments + '/images/PSM_simple.png', True, 600, -10.0, 0.1)
372  #generateRuntimePlot(pathToExperiments + '/simple/runtime/ISM', pathToExperiments + '/images/ISM_simple.png', False, 25, -0.7, 0.1)
373  #generateRuntimePlot(pathToExperiments + '/complex/runtime/PSM', pathToExperiments + '/images/PSM_complex.png', True, 600, -10.0, 0.1)
374  #generateRuntimePlot(pathToExperiments + '/complex/runtime/ISM', pathToExperiments + '/images/ISM_complex.png', False, 25, -0.7, 0.1)
375 
376  generateRuntimePlotStandalone(pathToExperiments + '/standalone/runtime/PSM', pathToExperiments + '/images/PSM_standalone.png', 5, False, -1.2, 0.05)
377  #generateRuntimePlotKickass(pathToExperiments + '/kickass/runtime/PSM', pathToExperiments + '/images/PSM_kickass.png', 8, False, True)
378  #generateRuntimePlotKickass(pathToExperiments + '/kickass/runtime/ISM', pathToExperiments + '/images/ISM_kickass.png', 8, False, False)
379 
380 if __name__ == "__main__":
381  main()
def generateRuntimePlotStandalone(pathToCsv, pathToImage, maxSceneobjects, useLog, textoffsetX, textoffsetY)
Definition: createPlots.py:163
def generateRuntimePlot(pathToCsv, pathToImage, meanOverTurns, xtics, textoffsetX, textoffsetY)
Definition: createPlots.py:32
def generateRuntimePlotKickass(pathToCsv, pathToImage, maxSceneobjects, useLog, meanOverTurns)
Definition: createPlots.py:286


asr_psm
Author(s): Braun Kai, Gehrung Joachim, Heizmann Heinrich, Meißner Pascal
autogenerated on Fri Nov 15 2019 03:57:54