annotate scripts/generate_report.py @ 2212:279733b3b67e

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