annotate python/timeline_view.py @ 3141:335bc77627e0 tip

fixing discrete interface to allow labels to display
author Dave Moffat <me@davemoffat.com>
date Mon, 26 Jul 2021 12:15:24 +0100
parents 185232d01324
children
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 # bar height (<1 to avoid overlapping)
b@2264 46 bar_height = 0.6
b@2264 47
b@2264 48 # figure size
b@2264 49 fig_width = 25
b@2264 50 fig_height = 5
b@2264 51
b@2264 52
b@2264 53 # CODE
b@2264 54
b@2264 55 # create timeline_folder if not yet created
b@2264 56 if not os.path.exists(timeline_folder):
b@2264 57 os.makedirs(timeline_folder)
b@2264 58
b@2264 59 # get every XML file in folder
b@2264 60 for file in os.listdir(folder_name):
b@2264 61 if file.endswith(".xml"):
b@2264 62 tree = ET.parse(folder_name + '/' + file)
b@2264 63 root = tree.getroot()
b@2264 64 subject_id = file[:-4] # drop '.xml'
b@2264 65
b@2264 66 # ONE TIMELINE PER PAGE - make new plot per page
b@2264 67
b@2264 68 # get list of all page names
b@2264 69 for audioholder in root.findall("./page"): # iterate over pages
b@2264 70 page_name = audioholder.get('ref') # get page name
b@2264 71 plot_empty = True # check if any data is plotted
b@2264 72
b@2264 73 if page_name is None: # ignore 'empty' audio_holders
b@2274 74 print("WARNING: " + file + " contains empty page. (comment_parser.py)")
b@2264 75 break
b@2264 76
b@2264 77 if audioholder.get("state") != "complete":
b@2274 78 print("WARNING: " + file + "test page " + page_name + " is not complete, skipping.")
b@2264 79 break;
b@2264 80 # SORT AUDIO ELEMENTS ALPHABETICALLY
b@2264 81 audioelements = audioholder.findall("./audioelement")
b@2264 82
b@2264 83 data = []
b@2264 84 for elem in audioelements: # from http://effbot.org/zone/element-sort.htm
b@2264 85 key = elem.get("ref")
b@2264 86 data.append((key, elem))
b@2264 87 data.sort()
b@2264 88
b@2264 89 N_audioelements = len(audioelements) # number of audio elements for this page
b@2264 90 increment = 0 # increased for every new audioelement
b@2264 91 audioelements_names = [] # store names of audioelements
b@2264 92
b@2264 93 # get axes handle
b@2264 94 fig = plt.figure(figsize=(fig_width, fig_height))
b@2264 95 ax = fig.add_subplot(111) #, aspect='equal'
b@2264 96
b@2264 97 # for page [page_name], print comments related to fragment [id]
b@2264 98 for tuple in data:
b@2264 99 audioelement = tuple[1]
b@2264 100 if audioelement is not None: # Check it exists
b@2264 101 audio_id = str(audioelement.get('ref'))
b@2264 102 audioelements_names.append(audio_id)
b@2264 103
b@2264 104 # for this audioelement, loop over all listen events
b@2281 105 listen_events = audioelement.findall("./metric/metricresult/[@name='elementListenTracker']/event")
b@2264 106 for event in listen_events:
b@2264 107 # mark this plot as not empty
b@2264 108 plot_empty = False
b@2264 109
b@2264 110 # get testtime: start and stop
b@2276 111 start_time = float(event.find('testtime').get('start'))
b@2276 112 stop_time = float(event.find('testtime').get('stop'))
b@2264 113 # event lines:
b@2264 114 ax.plot([start_time, start_time], # x-values
b@2264 115 [0, N_audioelements+1], # y-values
b@2264 116 color='k'
b@2264 117 )
b@2264 118 ax.plot([stop_time, stop_time], # x-values
b@2264 119 [0, N_audioelements+1], # y-values
b@2264 120 color='k'
b@2264 121 )
b@2264 122 # plot time:
b@2264 123 ax.add_patch(
b@2264 124 patches.Rectangle(
b@2264 125 (start_time, N_audioelements-increment-bar_height/2), # (x, y)
b@2264 126 stop_time - start_time, # width
b@2264 127 bar_height, # height
b@2264 128 color=colormap[increment%len(colormap)] # colour
b@2264 129 )
b@2264 130 )
b@2264 131
b@2264 132 increment+=1 # to next audioelement
b@2264 133
b@2264 134 if not plot_empty:
b@2264 135 # set plot parameters
b@2264 136 plt.title('Timeline ' + file + ": "+page_name)
b@2264 137 plt.xlabel('Time [seconds]')
b@2264 138 plt.ylabel('Fragment')
b@2264 139 plt.ylim(0, N_audioelements+1)
b@2264 140
b@2264 141 #y-ticks: fragment IDs, top to bottom
b@2264 142 plt.yticks(range(N_audioelements, 0, -1), audioelements_names) # show fragment names
b@2264 143
b@2264 144 #plt.show() # uncomment to show plot; comment when just saving
b@2264 145 #exit()
b@2264 146
b@2264 147 plt.savefig(timeline_folder+subject_id+"-"+page_name+".pdf", bbox_inches='tight')
b@2264 148 plt.close()
b@2264 149
b@2264 150 #TODO: if 'nonsensical' or unknown: dashed line until next event
b@2264 151 #TODO: Vertical lines for fragment looping point
b@2264 152