annotate python/timeline_view.py @ 2274:2b5990868aa7

timeline_view.py and timeline_view_movement.py compatible with Python 2.7 and 3.x: print ... --> print(...)
author Brecht De Man <b.deman@qmul.ac.uk>
date Wed, 20 Apr 2016 19:12:16 +0200
parents 556b79c72eee
children 3004c6a5665c
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 # COMMAND LINE ARGUMENTS
b@2264 10
b@2264 11 assert len(sys.argv)<3, "timeline_view takes at most 1 command line argument\n"+\
b@2264 12 "Use: python timeline_view.py [XML_files_location]"
b@2264 13
b@2264 14 # XML results files location
b@2264 15 if len(sys.argv) == 1:
b@2264 16 folder_name = "../saves" # Looks in 'saves/' folder from 'scripts/' folder
b@2274 17 print("Use: python timeline_view.py [XML_files_location]")
b@2274 18 print("Using default path: " + folder_name)
b@2264 19 elif len(sys.argv) == 2:
b@2264 20 folder_name = sys.argv[1] # First command line argument is folder
b@2264 21
b@2264 22 # check if folder_name exists
b@2264 23 if not os.path.exists(folder_name):
b@2264 24 #the file is not there
b@2274 25 print("Folder '"+folder_name+"' does not exist.")
b@2264 26 sys.exit() # terminate script execution
b@2264 27 elif not os.access(os.path.dirname(folder_name), os.W_OK):
b@2264 28 #the file does exist but write privileges are not given
b@2274 29 print("No write privileges in folder '"+folder_name+"'.")
b@2264 30
b@2264 31
b@2264 32 # CONFIGURATION
b@2264 33
b@2264 34 # Folder where to store timelines
b@2264 35 timeline_folder = folder_name + '/timelines/' # Stores in 'saves/timelines/'
b@2264 36
b@2264 37 # Font settings
b@2264 38 font = {'weight' : 'bold',
b@2264 39 'size' : 16}
b@2264 40 plt.rc('font', **font)
b@2264 41
b@2264 42 # Colormap for to cycle through
b@2264 43 colormap = ['b', 'r', 'g', 'c', 'm', 'y', 'k']
b@2264 44
b@2264 45 # if enabled, x-axis shows time per audioholder, not total test time
b@2264 46 show_audioholder_time = True
b@2264 47
b@2264 48 # bar height (<1 to avoid overlapping)
b@2264 49 bar_height = 0.6
b@2264 50
b@2264 51 # figure size
b@2264 52 fig_width = 25
b@2264 53 fig_height = 5
b@2264 54
b@2264 55
b@2264 56 # CODE
b@2264 57
b@2264 58 # create timeline_folder if not yet created
b@2264 59 if not os.path.exists(timeline_folder):
b@2264 60 os.makedirs(timeline_folder)
b@2264 61
b@2264 62 # get every XML file in folder
b@2264 63 for file in os.listdir(folder_name):
b@2264 64 if file.endswith(".xml"):
b@2264 65 tree = ET.parse(folder_name + '/' + file)
b@2264 66 root = tree.getroot()
b@2264 67 subject_id = file[:-4] # drop '.xml'
b@2264 68
b@2264 69 time_offset = 0 # test starts at zero
b@2264 70
b@2264 71 # ONE TIMELINE PER PAGE - make new plot per page
b@2264 72
b@2264 73 # get list of all page names
b@2264 74 for audioholder in root.findall("./page"): # iterate over pages
b@2264 75 page_name = audioholder.get('ref') # get page name
b@2264 76 plot_empty = True # check if any data is plotted
b@2264 77
b@2264 78 if page_name is None: # ignore 'empty' audio_holders
b@2274 79 print("WARNING: " + file + " contains empty page. (comment_parser.py)")
b@2264 80 break
b@2264 81
b@2264 82 if audioholder.get("state") != "complete":
b@2274 83 print("WARNING: " + file + "test page " + page_name + " is not complete, skipping.")
b@2264 84 break;
b@2264 85 # SORT AUDIO ELEMENTS ALPHABETICALLY
b@2264 86 audioelements = audioholder.findall("./audioelement")
b@2264 87
b@2264 88 data = []
b@2264 89 for elem in audioelements: # from http://effbot.org/zone/element-sort.htm
b@2264 90 key = elem.get("ref")
b@2264 91 data.append((key, elem))
b@2264 92 data.sort()
b@2264 93
b@2264 94 N_audioelements = len(audioelements) # number of audio elements for this page
b@2264 95 increment = 0 # increased for every new audioelement
b@2264 96 audioelements_names = [] # store names of audioelements
b@2264 97
b@2264 98 # get axes handle
b@2264 99 fig = plt.figure(figsize=(fig_width, fig_height))
b@2264 100 ax = fig.add_subplot(111) #, aspect='equal'
b@2264 101
b@2264 102 # for page [page_name], print comments related to fragment [id]
b@2264 103 for tuple in data:
b@2264 104 audioelement = tuple[1]
b@2264 105 if audioelement is not None: # Check it exists
b@2264 106 audio_id = str(audioelement.get('ref'))
b@2264 107 audioelements_names.append(audio_id)
b@2264 108
b@2264 109 # for this audioelement, loop over all listen events
b@2264 110 listen_events = audioelement.findall("./metric/metricResult/[@name='elementListenTracker']/event")
b@2264 111 for event in listen_events:
b@2264 112 # mark this plot as not empty
b@2264 113 plot_empty = False
b@2264 114
b@2264 115 # get testtime: start and stop
b@2264 116 start_time = float(event.find('testtime').get('start'))-time_offset
b@2264 117 stop_time = float(event.find('testtime').get('stop'))-time_offset
b@2264 118 # event lines:
b@2264 119 ax.plot([start_time, start_time], # x-values
b@2264 120 [0, N_audioelements+1], # y-values
b@2264 121 color='k'
b@2264 122 )
b@2264 123 ax.plot([stop_time, stop_time], # x-values
b@2264 124 [0, N_audioelements+1], # y-values
b@2264 125 color='k'
b@2264 126 )
b@2264 127 # plot time:
b@2264 128 ax.add_patch(
b@2264 129 patches.Rectangle(
b@2264 130 (start_time, N_audioelements-increment-bar_height/2), # (x, y)
b@2264 131 stop_time - start_time, # width
b@2264 132 bar_height, # height
b@2264 133 color=colormap[increment%len(colormap)] # colour
b@2264 134 )
b@2264 135 )
b@2264 136
b@2264 137 increment+=1 # to next audioelement
b@2264 138
b@2264 139 # subtract total audioholder length from subsequent audioholder event times
b@2264 140 audioholder_time = audioholder.find("./metric/metricresult/[@id='testTime']")
b@2264 141 if audioholder_time is not None and show_audioholder_time:
b@2264 142 time_offset = float(audioholder_time.text)
b@2264 143
b@2264 144 if not plot_empty:
b@2264 145 # set plot parameters
b@2264 146 plt.title('Timeline ' + file + ": "+page_name)
b@2264 147 plt.xlabel('Time [seconds]')
b@2264 148 plt.ylabel('Fragment')
b@2264 149 plt.ylim(0, N_audioelements+1)
b@2264 150
b@2264 151 #y-ticks: fragment IDs, top to bottom
b@2264 152 plt.yticks(range(N_audioelements, 0, -1), audioelements_names) # show fragment names
b@2264 153
b@2264 154
b@2264 155 #plt.show() # uncomment to show plot; comment when just saving
b@2264 156 #exit()
b@2264 157
b@2264 158 plt.savefig(timeline_folder+subject_id+"-"+page_name+".pdf", bbox_inches='tight')
b@2264 159 plt.close()
b@2264 160
b@2264 161 #TODO: if 'nonsensical' or unknown: dashed line until next event
b@2264 162 #TODO: Vertical lines for fragment looping point
b@2264 163