annotate python/timeline_view_movement.py @ 3109:63086deafdf4

Merge branch 'vnext' into Dev_main
author Nicholas Jillings <nicholas.jillings@mail.bcu.ac.uk>
date Tue, 10 Apr 2018 10:23:08 +0100
parents eaa5dc4aedbf
children 9ac4f490a1d8
rev   line source
b@2264 1 #!/usr/bin/python
b@2264 2
b@2264 3 import xml.etree.ElementTree as ET
b@2264 4 import os # list files in directory
b@2264 5 import sys # command line arguments
b@2264 6 import matplotlib.pyplot as plt # plots
b@2264 7 import matplotlib.patches as patches # rectangles
b@2264 8
b@2264 9
b@2264 10 # COMMAND LINE ARGUMENTS
b@2264 11
b@2264 12 assert len(sys.argv)<3, "timeline_view_movement takes at most 1 command line argument\n"+\
b@2264 13 "Use: python timeline_view_movement.py [XML_files_location]"
b@2264 14
b@2264 15 # XML results files location
b@2264 16 if len(sys.argv) == 1:
b@2264 17 folder_name = "../saves" # Looks in 'saves/' folder from 'scripts/' folder
b@2274 18 print("Use: python timeline_view_movement.py [XML_files_location]")
b@2274 19 print("Using default path: " + folder_name)
b@2264 20 elif len(sys.argv) == 2:
b@2264 21 folder_name = sys.argv[1] # First command line argument is folder
b@2264 22
b@2264 23 # check if folder_name exists
b@2264 24 if not os.path.exists(folder_name):
b@2264 25 #the file is not there
b@2274 26 print("Folder '"+folder_name+"' does not exist.")
b@2264 27 sys.exit() # terminate script execution
b@2264 28 elif not os.access(os.path.dirname(folder_name), os.W_OK):
b@2264 29 #the file does exist but write privileges are not given
b@2274 30 print("No write privileges in folder '"+folder_name+"'.")
b@2264 31
b@2264 32
b@2264 33 # CONFIGURATION
b@2264 34
b@2264 35 # Folder where to store timelines
b@2264 36 timeline_folder = folder_name + '/timelines_movement/' # Stores in 'saves/timelines_movement/' by default
b@2264 37
b@2264 38 # Font settings
b@2264 39 font = {'weight' : 'bold',
b@2264 40 'size' : 16}
b@2264 41 plt.rc('font', **font)
b@2264 42
b@2264 43 # Colormap for to cycle through
b@2264 44 colormap = ['b', 'g', 'c', 'm', 'y', 'k']
b@2264 45
b@2264 46 # figure size
b@2264 47 fig_width = 25
b@2264 48 fig_height = 10
b@2264 49
b@2264 50
b@2264 51 # CODE
b@2264 52
b@2264 53 # create timeline_folder if not yet created
b@2264 54 if not os.path.exists(timeline_folder):
b@2264 55 os.makedirs(timeline_folder)
b@2264 56
b@2264 57 # get every XML file in folder
b@2264 58 for file in os.listdir(folder_name):
b@2264 59 if file.endswith(".xml"):
b@2264 60 tree = ET.parse(folder_name + '/' + file)
b@2264 61 root = tree.getroot()
b@2264 62 subject_id = file[:-4] # drop '.xml'
b@2264 63
b@2264 64 previous_page_time = 0 # time spent before current page
b@2487 65 #time_offset = 0 # test starts at zero
b@2264 66
b@2264 67 # ONE TIMELINE PER PAGE - make new plot per page
b@2264 68
b@2264 69 # get list of all page names
b@2264 70 for page in root.findall("./page"): # iterate over pages
b@2264 71 page_name = page.get('ref') # get page name
b@2264 72 plot_empty = True # check if any data is plotted
b@2264 73
b@2264 74 if page_name is None: # ignore 'empty' audio_holders
b@2274 75 print("Skipping empty page name from "+subject_id+".")
b@2264 76 break
n@2995 77
n@2995 78 if page.get("state") != "complete":
n@2995 79 print("Skipping non-completed page "+page_name+" from "+subject_id+".")
n@2995 80 break
b@2264 81
b@2264 82 # subtract total page length from subsequent page event times
b@2264 83 page_time_temp = page.find("./metric/metricresult/[@id='testTime']")
b@2264 84 if page_time_temp is not None:
b@2264 85 page_time = float(page_time_temp.text)
b@2264 86 else:
b@2274 87 print("Skipping page without total time specified from "+subject_id+".")
b@2264 88 break
b@2264 89
b@2264 90 # get audioelements
b@2264 91 audioelements = page.findall("./audioelement")
b@2264 92
b@2264 93 # sort alphabetically
b@2264 94 data = []
b@2264 95 for elem in audioelements: # from http://effbot.org/zone/element-sort.htm
b@2264 96 key = elem.get("ref")
b@2264 97 data.append((key, elem))
b@2264 98 data.sort()
b@2264 99
b@2264 100 N_audioelements = len(audioelements) # number of audio elements for this page
b@2264 101 increment = 0 # increased for every new audioelement
b@2264 102
b@2264 103 # get axes handle
b@2264 104 fig = plt.figure(figsize=(fig_width, fig_height))
b@2264 105 ax = fig.add_subplot(111)
b@2264 106
b@2264 107 # for page [page_name], print comments related to fragment [id]
b@2264 108 #for tuple in data:
b@2264 109 # audioelement = tuple[1]
b@2264 110 for tuple in data:
b@2264 111 audioelement = tuple[1]
b@2264 112 if audioelement is not None: # Check it exists
b@2264 113 audio_id = str(audioelement.get('ref'))
b@2264 114
n@2996 115 # break if outside-reference
n@2996 116 if audioelement.get("type") == "outside-reference":
n@2996 117 break;
n@2996 118
n@2995 119 # break if no initial position....
b@2281 120 initial_position_temp = audioelement.find("./metric/metricresult/[@name='elementInitialPosition']")
b@2264 121 if initial_position_temp is None:
b@2274 122 print("Skipping "+page_name+" from "+subject_id+": does not have initial positions specified.")
b@2264 123 break
n@2995 124 # ... or move events registered
n@2995 125 movements = audioelement.find("./metric/metricresult[@name='elementTrackerFull']")
n@2995 126 if movements is None:
n@2995 127 print("Skipping "+page_name+" from "+subject_id+": does not have trackers.")
n@2995 128 break
b@2264 129
b@2264 130 # get move events, initial and eventual position
b@2264 131 initial_position = float(initial_position_temp.text)
b@2281 132 move_events = audioelement.findall("./metric/metricresult/[@name='elementTrackerFull']/movement")
b@2264 133 final_position = float(audioelement.find("./value").text)
b@2264 134
b@2264 135 # get listen events
b@2264 136 start_times_global = []
b@2264 137 stop_times_global = []
b@2281 138 listen_events = audioelement.findall("./metric/metricresult/[@name='elementListenTracker']/event")
b@2264 139 for event in listen_events:
b@2567 140 if event.find('testtime') is not None:
b@2567 141 # get testtime: start and stop
b@2567 142 start_times_global.append(float(event.find('testtime').get('start')))#-time_offset)
b@2567 143 stop_times_global.append(float(event.find('testtime').get('stop')))#-time_offset)
b@2264 144
b@2264 145 # display fragment name at start
b@2264 146 plt.text(0,initial_position+0.02,audio_id,color=colormap[increment%len(colormap)]) #,rotation=45
b@2264 147
b@2264 148 # previous position and time
b@2264 149 previous_position = initial_position
b@2264 150 previous_time = 0
b@2264 151
b@2264 152 # assume not playing at start
b@2264 153 currently_playing = False # keep track of whether fragment is playing during move event
b@2264 154
b@2264 155 # draw all segments except final one
b@2264 156 for event in move_events:
b@2264 157 # mark this plot as not empty
b@2264 158 plot_empty = False
b@2264 159
b@2264 160 # get time and final position of move event
b@2276 161 new_time = float(event.get("time")) #-time_offset # (legacy)
b@2264 162 new_position = float(event.get("value"))
b@2264 163
b@2264 164 # get play/stop events since last move until current move event
b@2264 165 stop_times = []
b@2264 166 start_times = []
b@2264 167 # is there a play and/or stop event between previous_time and new_time?
b@2264 168 for time in start_times_global:
b@2264 169 if time>previous_time and time<new_time:
b@2264 170 start_times.append(time)
b@2264 171 for time in stop_times_global:
b@2264 172 if time>previous_time and time<new_time:
b@2264 173 stop_times.append(time)
b@2264 174 # if no play/stop events between move events, find out whether playing
b@2264 175
b@2264 176 segment_start = previous_time # first segment starts at previous move event
b@2264 177
b@2264 178 # draw segments (horizontal line)
b@2264 179 while len(start_times)+len(stop_times)>0: # while still play/stop events left
b@2264 180 if len(stop_times)<1: # upcoming event is 'play'
b@2264 181 # draw non-playing segment from segment_start to 'play'
b@2264 182 currently_playing = False
b@2264 183 segment_stop = start_times.pop(0) # remove and return first item
b@2264 184 elif len(start_times)<1: # upcoming event is 'stop'
b@2264 185 # draw playing segment (red) from segment_start to 'stop'
b@2264 186 currently_playing = True
b@2264 187 segment_stop = stop_times.pop(0) # remove and return first item
b@2264 188 elif start_times[0]<stop_times[0]: # upcoming event is 'play'
b@2264 189 # draw non-playing segment from segment_start to 'play'
b@2264 190 currently_playing = False
b@2264 191 segment_stop = start_times.pop(0) # remove and return first item
b@2264 192 else: # stop_times[0]<start_times[0]: upcoming event is 'stop'
b@2264 193 # draw playing segment (red) from segment_start to 'stop'
b@2264 194 currently_playing = True
b@2264 195 segment_stop = stop_times.pop(0) # remove and return first item
b@2264 196
b@2264 197 # draw segment
b@2264 198 plt.plot([segment_start, segment_stop], # x-values
b@2264 199 [previous_position, previous_position], # y-values
b@2264 200 color='r' if currently_playing else colormap[increment%len(colormap)],
b@2264 201 linewidth=3
b@2264 202 )
b@2264 203 segment_start = segment_stop # move on to next segment
b@2264 204 currently_playing = not currently_playing # toggle to draw final segment correctly
b@2264 205
b@2264 206 # draw final segment (horizontal line) from last 'segment_start' to current move event time
b@2264 207 plt.plot([segment_start, new_time], # x-values
b@2264 208 [previous_position, previous_position], # y-values
b@2264 209 # color depends on playing during move event or not:
b@2264 210 color='r' if currently_playing else colormap[increment%len(colormap)],
b@2264 211 linewidth=3
b@2264 212 )
b@2264 213
b@2264 214 # vertical line from previous to current position
b@2264 215 plt.plot([new_time, new_time], # x-values
b@2264 216 [previous_position, new_position], # y-values
b@2264 217 # color depends on playing during move event or not:
b@2264 218 color='r' if currently_playing else colormap[increment%len(colormap)],
b@2264 219 linewidth=3
b@2264 220 )
b@2264 221
b@2264 222 # update previous_position value
b@2264 223 previous_position = new_position
b@2264 224 previous_time = new_time
b@2264 225
b@2264 226
b@2264 227
b@2264 228 # draw final horizontal segment (or only segment if audioelement not moved)
b@2264 229 # horizontal line from previous time to end of page
b@2264 230
b@2264 231 # get play/stop events since last move until current move event
b@2264 232 stop_times = []
b@2264 233 start_times = []
b@2264 234 # is there a play and/or stop event between previous_time and new_time?
b@2264 235 for time in start_times_global:
b@2276 236 if time>previous_time and time<page_time: #-time_offset:
b@2264 237 start_times.append(time)
b@2264 238 for time in stop_times_global:
b@2276 239 if time>previous_time and time<page_time: #-time_offset:
b@2264 240 stop_times.append(time)
b@2264 241 # if no play/stop events between move events, find out whether playing
b@2264 242
b@2264 243 segment_start = previous_time # first segment starts at previous move event
b@2264 244
b@2264 245 # draw segments (horizontal line)
b@2264 246 while len(start_times)+len(stop_times)>0: # while still play/stop events left
b@2264 247 # mark this plot as not empty
b@2264 248 plot_empty = False
b@2264 249 if len(stop_times)<1: # upcoming event is 'play'
b@2264 250 # draw non-playing segment from segment_start to 'play'
b@2264 251 currently_playing = False
b@2264 252 segment_stop = start_times.pop(0) # remove and return first item
b@2264 253 elif len(start_times)<1: # upcoming event is 'stop'
b@2264 254 # draw playing segment (red) from segment_start to 'stop'
b@2264 255 currently_playing = True
b@2264 256 segment_stop = stop_times.pop(0) # remove and return first item
b@2264 257 elif start_times[0]<stop_times[0]: # upcoming event is 'play'
b@2264 258 # draw non-playing segment from segment_start to 'play'
b@2264 259 currently_playing = False
b@2264 260 segment_stop = start_times.pop(0) # remove and return first item
b@2264 261 else: # stop_times[0]<start_times[0]: upcoming event is 'stop'
b@2264 262 # draw playing segment (red) from segment_start to 'stop'
b@2264 263 currently_playing = True
b@2264 264 segment_stop = stop_times.pop(0) # remove and return first item
b@2264 265
b@2264 266 # draw segment
b@2264 267 plt.plot([segment_start, segment_stop], # x-values
b@2264 268 [previous_position, previous_position], # y-values
b@2264 269 color='r' if currently_playing else colormap[increment%len(colormap)],
b@2264 270 linewidth=3
b@2264 271 )
b@2264 272 segment_start = segment_stop # move on to next segment
b@2264 273 currently_playing = not currently_playing # toggle to draw final segment correctly
b@2264 274
b@2264 275 # draw final segment (horizontal line) from last 'segment_start' to current move event time
b@2276 276 plt.plot([segment_start, page_time], # x-values
b@2264 277 [previous_position, previous_position], # y-values
b@2264 278 # color depends on playing during move event or not:
b@2264 279 color='r' if currently_playing else colormap[increment%len(colormap)],
b@2264 280 linewidth=3
b@2264 281 )
b@2264 282
b@2264 283 # plt.plot([previous_time, page_time-time_offset], # x-values
b@2264 284 # [previous_position, previous_position], # y-values
b@2264 285 # color=colormap[increment%len(colormap)],
b@2264 286 # linewidth=3
b@2264 287 # )
b@2264 288
b@2264 289 # display fragment name at end
b@2276 290 plt.text(page_time,previous_position,\
b@2264 291 audio_id,color=colormap[increment%len(colormap)]) #,rotation=45
b@2264 292
b@2264 293 increment+=1 # to next audioelement
b@2264 294
b@2276 295 last_page_duration = page_time #-time_offset
b@2487 296 #time_offset = page_time
b@2264 297
b@2276 298 if not plot_empty: # if plot is not empty, show and/or store
b@2264 299 # set plot parameters
b@2264 300 plt.title('Timeline ' + file + ": "+page_name)
b@2264 301 plt.xlabel('Time [seconds]')
b@2264 302 plt.xlim(0, last_page_duration)
b@2264 303 plt.ylabel('Rating') # default
b@2264 304 plt.ylim(0, 1) # rating between 0 and 1
b@2276 305
b@2568 306 # Y axis title and tick labels as specified in 'setup'
b@2568 307 # for corresponding page
b@2568 308 page_setup = root.find("./waet/page[@id='"+page_name+"']")
b@2568 309 # 'ref' of page is 'id' in page setup
b@2568 310
b@2276 311 # Different plots for different axes
b@2568 312 interfaces = page_setup.findall("./interface")
b@2568 313 interface_title = interfaces[0].find("./title")
b@2568 314 scales = interfaces[0].findall("./scales") # get first interface by default
n@2995 315
b@2568 316 labelpos = [] # array of scalelabel positions
b@2568 317 labelstr = [] # array of strings at labels
n@2995 318
n@2995 319 # No scales given. Use normal floats
n@2995 320 if len(scales) is 0:
n@2995 321 labelpos = [0.0, 1.0]
n@2995 322 labelstr = ["0", "100"]
n@2995 323 else:
n@2995 324 scalelabels = scales[0].findall("./scalelabel") # get first scale by default
n@2995 325
n@2995 326 for scalelabel in scalelabels:
n@2995 327 labelpos.append(float(scalelabel.get('position'))/100.0)
n@2995 328 labelstr.append(scalelabel.text)
b@2568 329
b@2568 330 # use interface name as Y axis label
b@2568 331 if interface_title is not None:
b@2568 332 plt.ylabel(interface_title.text)
b@2568 333 else:
b@2568 334 plt.ylabel('Rating') # default
b@2568 335
b@2568 336 if len(labelpos):
b@2568 337 plt.yticks(labelpos, labelstr)
b@2264 338
b@2264 339 #plt.show() # uncomment to show plot; comment when just saving
b@2264 340 #exit()
b@2264 341
b@2568 342 # save as PDF
b@2264 343 plt.savefig(timeline_folder+subject_id+"-"+page_name+".pdf", bbox_inches='tight')
b@2264 344 plt.close()