comparison scripts/generate_report.py @ 1942:4988c805ff9e

Update to WAC paper references
author Dave Moffat <me@davemoffat.com>
date Thu, 24 Sep 2015 09:49:01 +0100
parents
children 17b550310734 235594325b84
comparison
equal deleted inserted replaced
-1:000000000000 1942:4988c805ff9e
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 import xml.etree.ElementTree as ET
5 import os # for getting files from directory
6 import operator # for sorting data with multiple keys
7 import sys # for accessing command line arguments
8 import subprocess # for calling pdflatex
9 import shlex # for calling pdflatex
10 import matplotlib.pyplot as plt # plots
11 import numpy as np # numbers
12
13 # Command line arguments
14 assert len(sys.argv)<4, "evaluation_stats takes at most 2 command line argument\n"+\
15 "Use: python generate_report.py [results_folder] [no_render | -nr]"
16
17 render_figures = True
18
19 # XML results files location
20 if len(sys.argv) == 1:
21 folder_name = "../saves" # Looks in 'saves/' folder from 'scripts/' folder
22 print "Use: python generate_report.py [results_folder] [no_render | -nr]"
23 print "Using default path: " + folder_name
24 elif len(sys.argv) == 2:
25 folder_name = sys.argv[1] # First command line argument is folder
26 elif len(sys.argv) == 3:
27 folder_name = sys.argv[1] # First command line argument is folder
28 assert sys.argv[2] in ('no_render','-nr'), "Second argument not recognised. \n" +\
29 "Use: python generate_report.py [results_folder] [no_render | -nr]"
30 # Second command line argument is [no_render | -nr]
31 render_figures = False
32
33 def isNaN(num):
34 return num != num
35
36 # Turn number of seconds (int) to '[minutes] min [seconds] s' (string)
37 def seconds2timestr(time_in_seconds):
38 if time_in_seconds is not None and not isNaN(time_in_seconds):
39 time_in_minutes = int(time_in_seconds/60)
40 remaining_seconds = int(time_in_seconds%60)
41 return str(time_in_minutes) + " min " + str(remaining_seconds) + " s"
42 else:
43 return 'N/A'
44
45 # stats initialisation
46 number_of_XML_files = 0
47 number_of_pages = 0
48 number_of_fragments = 0
49 total_empty_comments = 0
50 total_not_played = 0
51 total_not_moved = 0
52 time_per_page_accum = 0
53
54 # arrays initialisation
55 page_names = []
56 real_page_names = [] # regardless of differing numbers of fragments
57 subject_count = [] # subjects per audioholder name
58 page_count = []
59 duration_page = [] # duration of experiment in function of page content
60 duration_order = [] # duration of experiment in function of page number
61 fragments_per_page = [] # number of fragments for corresponding page
62
63 # survey stats
64 gender = []
65 age = []
66
67 # get username if available
68 for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
69 user = os.environ.get(name)
70 if user:
71 break
72 else:
73 user = ''
74
75
76 # begin LaTeX document
77 header = r'''\documentclass[11pt, oneside]{article}
78 \usepackage{geometry}
79 \geometry{a4paper}
80 \usepackage[parfill]{parskip} % empty line instead of indent
81 \usepackage{graphicx} % figures
82 \usepackage{hyperref}
83 \usepackage{tikz} % pie charts
84 \title{Report}
85 \author{'''+\
86 user+\
87 r'''}
88 \graphicspath{{'''+\
89 folder_name+\
90 r'''/}}
91 %\setcounter{section}{-1} % Summary section 0 so number of sections equals number of files
92 \begin{document}
93 \maketitle
94 This is an automatically generated report using the `generate\_report.py' Python script
95 included with the Web Audio Evaluation Tool \cite{WAET} distribution which can be found
96 at \texttt{code.soundsoftware.ac.uk/projects/webaudioevaluationtool}.
97 \tableofcontents
98
99 '''
100
101 footer = '\n\t\t'+r'''\begin{thebibliography}{9}
102 \bibitem{WAET} % reference to accompanying publication
103 Nicholas Jillings, Brecht De Man, David Moffat and Joshua D. Reiss,
104 ``Web Audio Evaluation Tool: A browser-based listening test environment,''
105 presented at the 12th Sound and Music Computing Conference, July 2015.
106 \end{thebibliography}
107 \end{document}'''
108
109 body = ''
110
111 # generate images for later use
112 if render_figures:
113 subprocess.call("python timeline_view_movement.py "+folder_name, shell=True)
114 subprocess.call("python score_parser.py "+folder_name, shell=True)
115 subprocess.call("python score_plot.py "+folder_name, shell=True)
116
117 # get every XML file in folder
118 files_list = os.listdir(folder_name)
119 for file in files_list: # iterate over all files in files_list
120 if file.endswith(".xml"): # check if XML file
121 number_of_XML_files += 1
122 tree = ET.parse(folder_name + '/' + file)
123 root = tree.getroot()
124
125 # PRINT name as section
126 body+= '\n\section{'+file[:-4].capitalize()+'}\n' # make section header from name without extension
127
128 # reset for new subject
129 total_duration = 0
130 page_number = 0
131
132 individual_table = '\n' # table with stats for this individual test file
133 timeline_plots = '' # plots of timeline (movements and plays)
134
135 # DEMO survey stats
136 # get gender
137 this_subjects_gender = root.find("./posttest/radio/[@id='gender']")
138 if this_subjects_gender is not None:
139 gender.append(this_subjects_gender.get("name"))
140 else:
141 gender.append('UNAVAILABLE')
142 # get age
143 this_subjects_age = root.find("./posttest/number/[@id='age']")
144 if this_subjects_age is not None:
145 age.append(this_subjects_age.text)
146 #TODO add plot of age
147
148 # get list of all page names
149 for audioholder in root.findall("./audioholder"): # iterate over pages
150 page_name = audioholder.get('id') # get page name
151
152 if page_name is None: # ignore 'empty' audio_holders
153 print "WARNING: " + file + " contains empty audio holder. (evaluation_stats.py)"
154 break # move on to next
155
156 number_of_comments = 0 # for this page
157 number_of_missing_comments = 0 # for this page
158 not_played = [] # for this page
159 not_moved = [] # for this page
160
161 if audioholder.find("./metric/metricresult[@id='testTime']") is not None: # check if time is included
162 # 'testTime' keeps total duration: subtract time so far for duration of this audioholder
163 duration = float(audioholder.find("./metric/metricresult[@id='testTime']").text) - total_duration
164
165 # total duration of test
166 total_duration += duration
167 else:
168 duration = float('nan')
169 total_duration = float('nan')
170
171 # number of audio elements
172 audioelements = audioholder.findall("./audioelement") # get audioelements
173 number_of_fragments += len(audioelements) # add length of this list to total
174
175 # number of comments (interesting if comments not mandatory)
176 for audioelement in audioelements:
177 response = audioelement.find("./comment/response")
178 was_played = audioelement.find("./metric/metricresult/[@name='elementFlagListenedTo']")
179 was_moved = audioelement.find("./metric/metricresult/[@name='elementFlagMoved']")
180 if response.text is not None and len(response.text) > 1:
181 number_of_comments += 1
182 else:
183 number_of_missing_comments += 1
184 if was_played is not None and was_played.text == 'false':
185 not_played.append(audioelement.get('id'))
186 if was_moved is not None and was_moved.text == 'false':
187 not_moved.append(audioelement.get('id'))
188
189 # update global counters
190 total_empty_comments += number_of_missing_comments
191 total_not_played += len(not_played)
192 total_not_moved += len(not_moved)
193
194 # PRINT alerts when elements not played or markers not moved
195 # number of audio elements not played
196 if len(not_played) > 1:
197 body += '\t\t\\emph{\\textbf{ATTENTION: '+str(len(not_played))+\
198 ' fragments were not listened to in '+page_name+'! }}'+\
199 ', '.join(not_played)+'\\\\ \n'
200 if len(not_played) == 1:
201 body += '\t\t\\emph{\\textbf{ATTENTION: one fragment was not listened to in '+page_name+'! }}'+\
202 not_played[0]+'\\\\ \n'
203
204 # number of audio element markers not moved
205 if len(not_moved) > 1:
206 body += '\t\t\\emph{\\textbf{ATTENTION: '+str(len(not_moved))+\
207 ' markers were not moved in '+page_name+'! }}'+\
208 ', '.join(not_moved)+'\\\\ \n'
209 if len(not_moved) == 1:
210 body += '\t\t\\emph{\\textbf{ATTENTION: one marker was not moved in '+page_name+'! }}'+\
211 not_moved[0]+'\\\\ \n'
212
213 # PRINT song-specific statistic
214 individual_table += '\t\t'+page_name+'&'+\
215 str(number_of_comments) + '/' +\
216 str(number_of_comments+number_of_missing_comments)+'&'+\
217 seconds2timestr(duration)+'\\\\\n'
218
219 # get timeline for this audioholder
220 img_path = 'timelines_movement/'+file[:-4]+'-'+page_name+'.pdf'
221
222 # check if available
223 if os.path.isfile(folder_name+'/'+img_path):
224 # SHOW timeline image
225 timeline_plots += '\\includegraphics[width=\\textwidth]{'+\
226 folder_name+'/'+img_path+'}\n\t\t'
227
228 # keep track of duration in function of page index
229 if len(duration_order)>page_number:
230 duration_order[page_number].append(duration)
231 else:
232 duration_order.append([duration])
233
234 # keep list of audioholder ids and count how many times each audioholder id
235 # was tested, how long it took, and how many fragments there were
236 # (if number of fragments is different, store as different audioholder id)
237 if page_name in page_names:
238 page_index = page_names.index(page_name) # get index
239 # check if number of audioelements the same
240 if len(audioelements) == fragments_per_page[page_index]:
241 page_count[page_index] += 1
242 duration_page[page_index].append(duration)
243 else: # make new entry
244 alt_page_name = page_name+"("+str(len(audioelements))+")"
245 if alt_page_name in page_names: # if already there
246 alt_page_index = page_names.index(alt_page_name) # get index
247 page_count[alt_page_index] += 1
248 duration_page[alt_page_index].append(duration)
249 else:
250 page_names.append(alt_page_name)
251 page_count.append(1)
252 duration_page.append([duration])
253 fragments_per_page.append(len(audioelements))
254 else:
255 page_names.append(page_name)
256 page_count.append(1)
257 duration_page.append([duration])
258 fragments_per_page.append(len(audioelements))
259
260 # number of subjects per audioholder regardless of differing numbers of
261 # fragments (for inclusion in box plots)
262 if page_name in real_page_names:
263 page_index = real_page_names.index(page_name) # get index
264 subject_count[page_index] += 1
265 else:
266 real_page_names.append(page_name)
267 subject_count.append(1)
268
269 # bookkeeping
270 page_number += 1 # increase page count for this specific test
271 number_of_pages += 1 # increase total number of pages
272 time_per_page_accum += duration # total duration (for average time spent per page)
273
274 # PRINT table with statistics about this test
275 body += '\t\t'+r'''\begin{tabular}{|p{3.5cm}|c|p{2.5cm}|}
276 \hline
277 \textbf{Song name} & \textbf{Comments} & \textbf{Duration} \\ \hline '''+\
278 individual_table+'\t\t'+\
279 r'''\hline
280 \textbf{TOTAL} & & \textbf{'''+\
281 seconds2timestr(total_duration)+\
282 r'''}\\
283 \hline
284 \end{tabular}
285
286 '''
287 # PRINT timeline plots
288 body += timeline_plots
289
290 # join to footer
291 footer = body + footer
292
293 # empty body again
294 body = ''
295
296 # PRINT summary of everything (at start)
297 # unnumbered so that number of sections equals number of files
298 body += '\section*{Summary}\n\t\t\\addcontentsline{toc}{section}{Summary}\n'
299
300 # PRINT table with statistics
301 body += '\t\t\\begin{tabular}{ll}\n\t\t\t'
302 body += r'Number of XML files: &' + str(number_of_XML_files) + r'\\'+'\n\t\t\t'
303 body += r'Number of pages: &' + str(number_of_pages) + r'\\'+'\n\t\t\t'
304 body += r'Number of fragments: &' + str(number_of_fragments) + r'\\'+'\n\t\t\t'
305 body += r'Number of empty comments: &' + str(total_empty_comments) +\
306 " (" + str(round(100.0*total_empty_comments/number_of_fragments,2)) + r"\%)\\"+'\n\t\t\t'
307 body += r'Number of unplayed fragments: &' + str(total_not_played) +\
308 " (" + str(round(100.0*total_not_played/number_of_fragments,2)) + r"\%)\\"+'\n\t\t\t'
309 body += r'Number of unmoved markers: &' + str(total_not_moved) +\
310 " (" + str(round(100.0*total_not_moved/number_of_fragments,2)) + r"\%)\\"+'\n\t\t\t'
311 body += r'Average time per page: &' + seconds2timestr(time_per_page_accum/number_of_pages) + r"\\"+'\n\t\t'
312 body += '\\end{tabular} \\vspace{1.5cm} \\\\ \n'
313
314 # Average duration for first, second, ... page
315 body += "\t\t\\vspace{.5cm} \n\n\t\tAverage duration per page (see also Figure \\ref{fig:avgtimeperpage}): \\\\ \n\t\t"
316 body += r'''\begin{tabular}{lll}
317 \textbf{Page} & \textbf{Duration} & \textbf{\# subjects}\\'''
318 tpp_averages = [] # store average time per page
319 for page_number in range(len(duration_order)):
320 body += '\n\t\t\t'+str(page_number+1) + "&" +\
321 seconds2timestr(sum(duration_order[page_number])/len(duration_order[page_number])) +\
322 "&"+str(len(duration_order[page_number]))+r"\\"
323 tpp_averages.append(sum(duration_order[page_number])/len(duration_order[page_number]))
324
325 body += '\n\t\t\\end{tabular} \\vspace{1.5cm} \\\\ \n\n\t\t'
326
327 # SHOW bar plot of average time per page
328 plt.bar(range(1,len(duration_order)+1), np.array(tpp_averages)/60)
329 plt.xlabel('Page order')
330 plt.xlim(.8, len(duration_order)+1)
331 plt.xticks(np.arange(1,len(duration_order)+1)+.4, range(1,len(duration_order)+1))
332 plt.ylabel('Average time [minutes]')
333 plt.savefig(folder_name+"/time_per_page.pdf", bbox_inches='tight')
334 plt.close()
335 #TODO add error bars
336
337
338 # Sort pages by number of audioelements, then by duration
339
340 # average duration and number of subjects per page
341 average_duration_page = []
342 number_of_subjects_page = []
343 for line in duration_page:
344 number_of_subjects_page.append(len(line))
345 average_duration_page.append(sum(line)/len(line))
346
347 # combine and sort in function of number of audioelements and duration
348 combined_list = [page_names, average_duration_page, fragments_per_page, number_of_subjects_page]
349 combined_list = sorted(zip(*combined_list), key=operator.itemgetter(1, 2)) # sort
350
351 # Show average duration for all songs
352 body += r'''\vspace{.5cm}
353 Average duration per audioholder (see also Figure \ref{fig:avgtimeperaudioholder}): \\
354 \begin{tabular}{llll}
355 \textbf{Audioholder} & \textbf{Duration} & \textbf{\# subjects} & \textbf{\# fragments} \\'''
356 audioholder_names_ordered = []
357 average_duration_audioholder_ordered = []
358 number_of_subjects = []
359 for page_index in range(len(page_names)):
360 audioholder_names_ordered.append(combined_list[page_index][0])
361 average_duration_audioholder_ordered.append(combined_list[page_index][1])
362 number_of_subjects.append(combined_list[page_index][3])
363 body += '\n\t\t\t'+combined_list[page_index][0] + "&" +\
364 seconds2timestr(combined_list[page_index][1]) + "&" +\
365 str(combined_list[page_index][3]) + "&" +\
366 str(combined_list[page_index][2]) + r"\\"
367 body += '\n\t\t\\end{tabular}\n'
368
369 # SHOW bar plot of average time per page
370 plt.bar(range(1,len(audioholder_names_ordered)+1), np.array(average_duration_audioholder_ordered)/60)
371 plt.xlabel('Audioholder')
372 plt.xlim(.8, len(audioholder_names_ordered)+1)
373 plt.xticks(np.arange(1,len(audioholder_names_ordered)+1)+.4, audioholder_names_ordered, rotation=90)
374 plt.ylabel('Average time [minutes]')
375 plt.savefig(folder_name+"/time_per_audioholder.pdf", bbox_inches='tight')
376 plt.close()
377
378 # SHOW bar plot of average time per page
379 plt.bar(range(1,len(audioholder_names_ordered)+1), number_of_subjects)
380 plt.xlabel('Audioholder')
381 plt.xlim(.8, len(audioholder_names_ordered)+1)
382 plt.xticks(np.arange(1,len(audioholder_names_ordered)+1)+.4, audioholder_names_ordered, rotation=90)
383 plt.ylabel('Number of subjects')
384 ax = plt.gca()
385 ylims = ax.get_ylim()
386 yint = np.arange(int(np.floor(ylims[0])), int(np.ceil(ylims[1]))+1)
387 plt.yticks(yint)
388 plt.savefig(folder_name+"/subjects_per_audioholder.pdf", bbox_inches='tight')
389 plt.close()
390
391 # SHOW both figures
392 body += r'''
393 \begin{figure}[htbp]
394 \begin{center}
395 \includegraphics[width=.65\textwidth]{'''+\
396 folder_name+"/time_per_page.pdf"+\
397 r'''}
398 \caption{Average time spent per page.}
399 \label{fig:avgtimeperpage}
400 \end{center}
401 \end{figure}
402
403 '''
404 body += r'''\begin{figure}[htbp]
405 \begin{center}
406 \includegraphics[width=.65\textwidth]{'''+\
407 folder_name+"/time_per_audioholder.pdf"+\
408 r'''}
409 \caption{Average time spent per audioholder.}
410 \label{fig:avgtimeperaudioholder}
411 \end{center}
412 \end{figure}
413
414 '''
415 body += r'''\begin{figure}[htbp]
416 \begin{center}
417 \includegraphics[width=.65\textwidth]{'''+\
418 folder_name+"/subjects_per_audioholder.pdf"+\
419 r'''}
420 \caption{Number of subjects per audioholder.}
421 \label{fig:subjectsperaudioholder}
422 \end{center}
423 \end{figure}
424
425 '''
426 #TODO add error bars
427 #TODO layout of figures
428
429 # SHOW boxplot per audioholder
430 #TODO order in decreasing order of participants
431 for audioholder_name in page_names: # get each name
432 # plot boxplot if exists (not so for the 'alt' names)
433 if os.path.isfile(folder_name+'/ratings/'+audioholder_name+'-ratings-box.pdf'):
434 body += r'''\begin{figure}[htbp]
435 \begin{center}
436 \includegraphics[width=.65\textwidth]{'''+\
437 folder_name+"/ratings/"+audioholder_name+'-ratings-box.pdf'+\
438 r'''}
439 \caption{Box plot of ratings for audioholder '''+\
440 audioholder_name+' ('+str(subject_count[real_page_names.index(audioholder_name)])+\
441 ''' participants).}
442 \label{fig:boxplot'''+audioholder_name.replace(" ", "")+'''}
443 \end{center}
444 \end{figure}
445
446 '''
447
448 # DEMO pie chart of gender distribution among subjects
449 genders = ['male', 'female', 'other', 'preferNotToSay', 'UNAVAILABLE']
450 # TODO: get the above automatically
451 gender_distribution = ''
452 for item in genders:
453 number = gender.count(item)
454 if number>0:
455 gender_distribution += str("{:.2f}".format((100.0*number)/len(gender)))+\
456 '/'+item.capitalize()+' ('+str(number)+'),\n'
457
458 body += r'''
459 % Pie chart of gender distribution
460 \def\angle{0}
461 \def\radius{3}
462 \def\cyclelist{{"orange","blue","red","green"}}
463 \newcount\cyclecount \cyclecount=-1
464 \newcount\ind \ind=-1
465 \begin{figure}[htbp]
466 \begin{center}\begin{tikzpicture}[nodes = {font=\sffamily}]
467 \foreach \percent/\name in {'''+\
468 gender_distribution+\
469 r'''} {\ifx\percent\empty\else % If \percent is empty, do nothing
470 \global\advance\cyclecount by 1 % Advance cyclecount
471 \global\advance\ind by 1 % Advance list index
472 \ifnum6<\cyclecount % If cyclecount is larger than list
473 \global\cyclecount=0 % reset cyclecount and
474 \global\ind=0 % reset list index
475 \fi
476 \pgfmathparse{\cyclelist[\the\ind]} % Get color from cycle list
477 \edef\color{\pgfmathresult} % and store as \color
478 % Draw angle and set labels
479 \draw[fill={\color!50},draw={\color}] (0,0) -- (\angle:\radius)
480 arc (\angle:\angle+\percent*3.6:\radius) -- cycle;
481 \node at (\angle+0.5*\percent*3.6:0.7*\radius) {\percent\,\%};
482 \node[pin=\angle+0.5*\percent*3.6:\name]
483 at (\angle+0.5*\percent*3.6:\radius) {};
484 \pgfmathparse{\angle+\percent*3.6} % Advance angle
485 \xdef\angle{\pgfmathresult} % and store in \angle
486 \fi
487 };
488 \end{tikzpicture}
489 \caption{Representation of gender across subjects}
490 \label{default}
491 \end{center}
492 \end{figure}
493
494 '''
495 # problem: some people entered twice?
496
497 #TODO
498 # time per page in function of number of fragments (plot)
499 # time per participant in function of number of pages
500 # plot total time for each participant
501 # show 'count' per page (in order)
502
503 # clear up page_index <> page_count <> page_number confusion
504
505
506 texfile = header+body+footer # add bits together
507
508 # write TeX file
509 with open(folder_name + '/' + 'Report.tex','w') as f:
510 f.write(texfile)
511 proc=subprocess.Popen(shlex.split('pdflatex -output-directory='+folder_name+' '+ folder_name + '/Report.tex'))
512 proc.communicate()
513 # run again
514 proc=subprocess.Popen(shlex.split('pdflatex -output-directory='+folder_name+' '+ folder_name + '/Report.tex'))
515 proc.communicate()
516
517 #TODO remove auxiliary LaTeX files
518 try:
519 os.remove(folder_name + '/' + 'Report.aux')
520 os.remove(folder_name + '/' + 'Report.log')
521 os.remove(folder_name + '/' + 'Report.out')
522 os.remove(folder_name + '/' + 'Report.toc')
523 except OSError:
524 pass
525