comparison python/timeline_view_movement.py @ 2264:556b79c72eee

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