annotate scripts/generate_report.py @ 1810:7020aed2f8c6

Scripts: Generate PDF report on set of result XML files (using LaTeX)
author Brecht De Man <b.deman@qmul.ac.uk>
date Tue, 18 Aug 2015 23:56:05 +0200
parents
children 2c7dc66c102e
rev   line source
b@1810 1 #!/usr/bin/python
b@1810 2 # -*- coding: utf-8 -*-
b@1810 3
b@1810 4 import xml.etree.ElementTree as ET
b@1810 5 import os # for getting files from directory
b@1810 6 import operator # for sorting data with multiple keys
b@1810 7 import sys # for accessing command line arguments
b@1810 8 import subprocess # for calling pdflatex
b@1810 9 import shlex # for calling pdflatex
b@1810 10 import matplotlib.pyplot as plt # plots
b@1810 11 import numpy as np # numbers
b@1810 12
b@1810 13 # Command line arguments
b@1810 14 assert len(sys.argv)<3, "evaluation_stats takes at most 1 command line argument\n"+\
b@1810 15 "Use: python evaluation_stats.py [results_folder]"
b@1810 16
b@1810 17 # XML results files location
b@1810 18 if len(sys.argv) == 1:
b@1810 19 folder_name = "../saves" # Looks in 'saves/' folder from 'scripts/' folder
b@1810 20 print "Use: python evaluation_stats.py [results_folder]"
b@1810 21 print "Using default path: " + folder_name
b@1810 22 elif len(sys.argv) == 2:
b@1810 23 folder_name = sys.argv[1] # First command line argument is folder
b@1810 24
b@1810 25 # Turn number of seconds (int) to '[minutes] min [seconds] s' (string)
b@1810 26 def seconds2timestr(time_in_seconds):
b@1810 27 time_in_minutes = int(time_in_seconds/60)
b@1810 28 remaining_seconds = int(time_in_seconds%60)
b@1810 29 return str(time_in_minutes) + " min " + str(remaining_seconds) + " s"
b@1810 30
b@1810 31 # stats initialisation
b@1810 32 number_of_XML_files = 0
b@1810 33 number_of_pages = 0
b@1810 34 number_of_fragments = 0
b@1810 35 total_empty_comments = 0
b@1810 36 total_not_played = 0
b@1810 37 total_not_moved = 0
b@1810 38 time_per_page_accum = 0
b@1810 39
b@1810 40 # arrays initialisation
b@1810 41 page_names = []
b@1810 42 page_count = []
b@1810 43 duration_page = [] # duration of experiment in function of page content
b@1810 44 duration_order = [] # duration of experiment in function of page number
b@1810 45 fragments_per_page = [] # number of fragments for corresponding page
b@1810 46
b@1810 47 # get username if available
b@1810 48 for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
b@1810 49 user = os.environ.get(name)
b@1810 50 if user:
b@1810 51 break
b@1810 52 else:
b@1810 53 user = ''
b@1810 54
b@1810 55
b@1810 56 # begin LaTeX document
b@1810 57 header = r'''\documentclass[11pt, oneside]{article}
b@1810 58 \usepackage{geometry}
b@1810 59 \geometry{letterpaper}
b@1810 60 \usepackage[parfill]{parskip}
b@1810 61 \usepackage{graphicx}
b@1810 62 \title{Report}
b@1810 63 \author{'''+\
b@1810 64 user+\
b@1810 65 r'''}
b@1810 66 \graphicspath{{'''+\
b@1810 67 folder_name+\
b@1810 68 r'''/}}
b@1810 69 \begin{document}
b@1810 70 \maketitle
b@1810 71 \tableofcontents
b@1810 72 '''
b@1810 73
b@1810 74 footer = '\end{document}'
b@1810 75
b@1810 76 body = ''
b@1810 77
b@1810 78 # generate images for later use
b@1810 79 subprocess.call("timeline_view_movement.py", shell=True)
b@1810 80
b@1810 81 # get every XML file in folder
b@1810 82 files_list = os.listdir(folder_name)
b@1810 83 for file in files_list: # iterate over all files in files_list
b@1810 84 if file.endswith(".xml"): # check if XML file
b@1810 85 number_of_XML_files += 1
b@1810 86 tree = ET.parse(folder_name + '/' + file)
b@1810 87 root = tree.getroot()
b@1810 88
b@1810 89 # PRINT name as section
b@1810 90 body+= '\section{'+file[:-4].capitalize()+'}\n' # make section header from name without extension
b@1810 91
b@1810 92 # reset for new subject
b@1810 93 total_duration = 0
b@1810 94 page_number = 0
b@1810 95
b@1810 96 individual_table = '' # table with stats for this individual test file
b@1810 97
b@1810 98 # get list of all page names
b@1810 99 for audioholder in root.findall("./audioholder"): # iterate over pages
b@1810 100 page_name = audioholder.get('id') # get page name
b@1810 101
b@1810 102 if page_name is None: # ignore 'empty' audio_holders
b@1810 103 print "WARNING: " + file + " contains empty audio holder. (evaluation_stats.py)"
b@1810 104 break # move on to next
b@1810 105
b@1810 106 number_of_comments = 0 # for this page
b@1810 107 number_of_missing_comments = 0 # for this page
b@1810 108 not_played = 0 # for this page
b@1810 109 not_moved = 0 # for this page
b@1810 110
b@1810 111 # 'testTime' keeps total duration: subtract time so far for duration of this audioholder
b@1810 112 duration = float(audioholder.find("./metric/metricresult[@id='testTime']").text) - total_duration
b@1810 113
b@1810 114 # total duration of test
b@1810 115 total_duration += duration
b@1810 116
b@1810 117 # number of audio elements
b@1810 118 audioelements = audioholder.findall("./audioelement") # get audioelements
b@1810 119 number_of_fragments += len(audioelements) # add length of this list to total
b@1810 120
b@1810 121 # number of comments (interesting if comments not mandatory)
b@1810 122 for audioelement in audioelements:
b@1810 123 response = audioelement.find("./comment/response")
b@1810 124 was_played = audioelement.find("./metric/metricresult/[@name='elementFlagListenedTo']")
b@1810 125 was_moved = audioelement.find("./metric/metricresult/[@name='elementFlagMoved']")
b@1810 126 if response.text is not None and len(response.text) > 1:
b@1810 127 number_of_comments += 1
b@1810 128 else:
b@1810 129 number_of_missing_comments += 1
b@1810 130 if was_played is not None and was_played.text == 'false':
b@1810 131 not_played += 1
b@1810 132 if was_moved is not None and was_moved.text == 'false':
b@1810 133 not_moved += 1
b@1810 134
b@1810 135 # update global counters
b@1810 136 total_empty_comments += number_of_missing_comments
b@1810 137 total_not_played += not_played
b@1810 138 total_not_moved += not_moved
b@1810 139
b@1810 140 # PRINT alerts when elements not played or markers not moved
b@1810 141 # number of audio elements not played
b@1810 142 if not_played > 1:
b@1810 143 body += '\\emph{\\textbf{ATTENTION: '+str(not_played)+' fragments were not listened to in '+page_name+'!}} \\\\ \n'
b@1810 144 if not_played == 1:
b@1810 145 body += '\\emph{\\textbf{ATTENTION: one fragment was not listened to in '+page_name+'!}} \\\\ \n '
b@1810 146
b@1810 147 # number of audio element markers not moved
b@1810 148 if not_moved > 1:
b@1810 149 body += '\\emph{\\textbf{ATTENTION: '+str(not_moved)+' markers were not moved in '+page_name+'!}} \\\\ \n'
b@1810 150 if not_moved == 1:
b@1810 151 body += '\\emph{\\textbf{ATTENTION: one marker was not moved in '+page_name+'!}} \\\\ \n'
b@1810 152
b@1810 153 #TODO which one not moved/listened to?
b@1810 154
b@1810 155 # PRINT song-specific statistic
b@1810 156 individual_table += page_name+'&'+\
b@1810 157 str(number_of_comments) + '/' +\
b@1810 158 str(number_of_comments+number_of_missing_comments)+'&'+\
b@1810 159 seconds2timestr(duration)+'\\\\'
b@1810 160
b@1810 161 # get timeline for this audioholder
b@1810 162 img_path = 'timelines_movement/'+file[:-4]+'-'+page_name+'.pdf'
b@1810 163
b@1810 164 # check if available
b@1810 165 if os.path.isfile(folder_name+'/'+img_path):
b@1810 166 # SHOW timeline image
b@1810 167 body += r'''\begin{figure}[htbp]
b@1810 168 \begin{center}
b@1810 169 \includegraphics[width=\textwidth]{'''+\
b@1810 170 folder_name+'/'+img_path+\
b@1810 171 r'''}
b@1810 172 \caption{Timeline of '''+\
b@1810 173 page_name+' by '+ file[:-4].capitalize() +\
b@1810 174 r'''.}
b@1810 175 \end{center}
b@1810 176 \end{figure}
b@1810 177 '''
b@1810 178
b@1810 179 # keep track of duration in function of page index
b@1810 180 if len(duration_order)>page_number:
b@1810 181 duration_order[page_number].append(duration)
b@1810 182 else:
b@1810 183 duration_order.append([duration])
b@1810 184
b@1810 185 # keep list of audioholder ids and count how many times each audioholder id
b@1810 186 # was tested, how long it took, and how many fragments there were (if number of
b@1810 187 # fragments is different, store as different audioholder id)
b@1810 188 if page_name in page_names:
b@1810 189 page_index = page_names.index(page_name) # get index
b@1810 190 # check if number of audioelements the same
b@1810 191 if len(audioelements) == fragments_per_page[page_index]:
b@1810 192 page_count[page_index] += 1
b@1810 193 duration_page[page_index].append(duration)
b@1810 194 else: # make new entry
b@1810 195 alt_page_name = page_name+"("+str(len(audioelements))+")"
b@1810 196 if alt_page_name in page_names: # if already there
b@1810 197 alt_page_index = page_names.index(alt_page_name) # get index
b@1810 198 page_count[alt_page_index] += 1
b@1810 199 duration_page[alt_page_index].append(duration)
b@1810 200 else:
b@1810 201 page_names.append(alt_page_name)
b@1810 202 page_count.append(1)
b@1810 203 duration_page.append([duration])
b@1810 204 fragments_per_page.append(len(audioelements))
b@1810 205 else:
b@1810 206 page_names.append(page_name)
b@1810 207 page_count.append(1)
b@1810 208 duration_page.append([duration])
b@1810 209 fragments_per_page.append(len(audioelements))
b@1810 210
b@1810 211 # bookkeeping
b@1810 212 page_number += 1 # increase page count for this specific test
b@1810 213 number_of_pages += 1 # increase total number of pages
b@1810 214 time_per_page_accum += duration # total duration (for average time spent per page)
b@1810 215
b@1810 216 # PRINT table with statistics about this test
b@1810 217 body += r'''\begin{tabular}{|p{3.5cm}|c|p{2.5cm}|}
b@1810 218 \hline
b@1810 219 \textbf{Song name} & \textbf{Comments} & \textbf{Duration} \\ \hline '''+\
b@1810 220 individual_table+\
b@1810 221 r'''\hline
b@1810 222 \textbf{TOTAL} & & \textbf{'''+\
b@1810 223 seconds2timestr(total_duration)+\
b@1810 224 r'''}\\
b@1810 225 \hline
b@1810 226 \end{tabular}'''
b@1810 227
b@1810 228 # join to footer
b@1810 229 footer = body + footer
b@1810 230
b@1810 231 # empty body again
b@1810 232 body = ''
b@1810 233
b@1810 234 # PRINT summary of everything (at start)
b@1810 235 body += '\section{Summary}\n'
b@1810 236
b@1810 237 # PRINT table with statistics
b@1810 238 body += '\\begin{tabular}{ll}'
b@1810 239 body += r'Number of XML files: &' + str(number_of_XML_files) + r'\\'
b@1810 240 body += r'Number of pages: &' + str(number_of_pages) + r'\\'
b@1810 241 body += r'Number of fragments: &' + str(number_of_fragments) + r'\\'
b@1810 242 body += r'Number of empty comments: &' + str(total_empty_comments) +\
b@1810 243 " (" + str(round(100.0*total_empty_comments/number_of_fragments,2)) + r"\%)\\"
b@1810 244 body += r'Number of unplayed fragments: &' + str(total_not_played) +\
b@1810 245 " (" + str(round(100.0*total_not_played/number_of_fragments,2)) + r"\%)\\"
b@1810 246 body += r'Number of unmoved markers: &' + str(total_not_moved) +\
b@1810 247 " (" + str(round(100.0*total_not_moved/number_of_fragments,2)) + r"\%)\\"
b@1810 248 body += r'Average time per page: &' + seconds2timestr(time_per_page_accum/number_of_pages) + r"\\"
b@1810 249
b@1810 250
b@1810 251 # Pages and number of times tested
b@1810 252 page_count_strings = list(str(x) for x in page_count)
b@1810 253 count_list = page_names + page_count_strings
b@1810 254 count_list[::2] = page_names
b@1810 255 count_list[1::2] = page_count_strings
b@1810 256 #body += r'Pages tested: &' + str(count_list) + r"\\"
b@1810 257
b@1810 258 body += '\\end{tabular} \\vspace{1.5cm} \\\\ \n'
b@1810 259
b@1810 260 # Average duration for first, second, ... page
b@1810 261 body += " \\vspace{.5cm} Average duration per page (see also Figure \\ref{fig:avgtimeperpage}): \\\\ \n"
b@1810 262 body += r'''\begin{tabular}{lll}
b@1810 263 \textbf{Page} & \textbf{Duration} & \textbf{\# subjects}\\
b@1810 264 '''
b@1810 265 tpp_averages = [] # store average time per page
b@1810 266 for page_number in range(len(duration_order)):
b@1810 267 body += str(page_number+1) + "&" +\
b@1810 268 seconds2timestr(sum(duration_order[page_number])/len(duration_order[page_number])) +\
b@1810 269 "&"+str(len(duration_order[page_number]))+r"\\"
b@1810 270 tpp_averages.append(sum(duration_order[page_number])/len(duration_order[page_number]))
b@1810 271
b@1810 272 body += '\\end{tabular} \\vspace{1.5cm} \\\\ \n'
b@1810 273
b@1810 274 # SHOW bar plot of average time per page
b@1810 275 plt.bar(range(1,len(duration_order)+1), tpp_averages)
b@1810 276 plt.xlabel('Page')
b@1810 277 plt.xlim(.8, len(duration_order)+1)
b@1810 278 plt.xticks(np.arange(1,len(duration_order)+1)+.4, range(1,len(duration_order)+1))
b@1810 279 plt.ylabel('Time [seconds]')
b@1810 280 plt.savefig(folder_name+"/time_per_page.pdf", bbox_inches='tight')
b@1810 281 plt.close()
b@1810 282 body += r'''\begin{figure}[htbp]
b@1810 283 \begin{center}
b@1810 284 \includegraphics[width=\textwidth]{'''+\
b@1810 285 folder_name+"/time_per_page.pdf"+\
b@1810 286 r'''}
b@1810 287 \caption{Average time spent per audioholder page.}
b@1810 288 \label{fig:avgtimeperpage}
b@1810 289 \end{center}
b@1810 290 \end{figure}
b@1810 291 '''
b@1810 292 #TODO add error bars
b@1810 293
b@1810 294
b@1810 295 # Sort pages by number of audioelements, then by duration
b@1810 296
b@1810 297 # average duration and number of subjects per page
b@1810 298 average_duration_page = []
b@1810 299 number_of_subjects_page = []
b@1810 300 for line in duration_page:
b@1810 301 number_of_subjects_page.append(len(line))
b@1810 302 average_duration_page.append(sum(line)/len(line))
b@1810 303
b@1810 304 # combine and sort in function of number of audioelements and duration
b@1810 305 combined_list = [page_names, average_duration_page, fragments_per_page, number_of_subjects_page]
b@1810 306 combined_list = sorted(zip(*combined_list), key=operator.itemgetter(1, 2)) # sort
b@1810 307
b@1810 308 # Show average duration for all songs
b@1810 309 body += r'''\vspace{.5cm} Average duration per audioholder: \\
b@1810 310 \begin{tabular}{llll}
b@1810 311 \textbf{Audioholder} & \textbf{Duration} & \textbf{\# subjects} & \textbf{\# fragments} \\
b@1810 312 '''
b@1810 313 for page_index in range(len(page_names)):
b@1810 314 body += combined_list[page_index][0] + "&" +\
b@1810 315 seconds2timestr(combined_list[page_index][1]) + "&" +\
b@1810 316 str(combined_list[page_index][3]) + "&" +\
b@1810 317 str(combined_list[page_index][2]) + r"\\"
b@1810 318 body += '\\end{tabular}\n'
b@1810 319
b@1810 320 #TODO
b@1810 321 # time per page in function of number of fragments (plot)
b@1810 322 # time per participant in function of number of pages
b@1810 323 # plot total time for each participant
b@1810 324 # plot total time
b@1810 325 # show 'count' per page (in order)
b@1810 326
b@1810 327 # clear up page_index <> page_count <> page_number confusion
b@1810 328
b@1810 329
b@1810 330 texfile = header+body+footer
b@1810 331
b@1810 332 # write TeX file
b@1810 333 with open(folder_name + '/' + 'test.tex','w') as f:
b@1810 334 f.write(texfile)
b@1810 335 proc=subprocess.Popen(shlex.split('pdflatex -output-directory='+folder_name+' '+ folder_name + '/test.tex'))
b@1810 336 proc.communicate()
b@1810 337 # run again
b@1810 338 proc=subprocess.Popen(shlex.split('pdflatex -output-directory='+folder_name+' '+ folder_name + '/test.tex'))
b@1810 339 proc.communicate()
b@1810 340
b@1810 341 #TODO remove auxiliary LaTeX files