annotate python/score_plot.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 fc25720c1a01
children
rev   line source
b@2264 1 #!/usr/bin/python
b@2264 2
b@2264 3 import sys
b@2264 4 import os
b@2264 5 import csv
b@2264 6 import matplotlib.pyplot as plt
b@2264 7 import numpy as np
b@2264 8 import scipy as sp
b@2264 9 import scipy.stats
b@2264 10
b@2264 11 # COMMAND LINE ARGUMENTS
b@2264 12
b@2264 13 #TODO: Merge, implement this functionality
b@2264 14 #TODO: Control by CLI arguments (plot types, save and/or show, ...)
b@2264 15
b@2264 16 assert len(sys.argv)<4, "score_plot takes at most 2 command line arguments\n"+\
b@2264 17 "Use: python score_plot.py [ratings_folder_location]."+\
b@2264 18 "Type 'python score_plot.py -h' for more options"
b@2264 19
b@2264 20 # initialise plot types (false by default) and options
b@2264 21 enable_boxplot = False # show box plot
b@2264 22 enable_confidence = False # show confidence interval
nicholas@3107 23 enable_combined = False # show combined plots
b@2264 24 confidence = 0.90 # confidence value (for confidence interval plot)
b@2264 25 enable_individual = False # show all individual ratings
b@2264 26 show_individual = [] # show specific individuals (empty: show all individuals found)
b@2264 27 show_legend = False # show names of individuals
b@2264 28
b@2264 29 # DEFAULT: Looks in 'saves/ratings/' folder from 'scripts/' folder
b@2264 30 rating_folder = "../saves/ratings/"
b@2264 31
b@2264 32 # XML results files location
b@2264 33 if len(sys.argv) == 1: # no extra arguments
b@2264 34 enable_boxplot = True # show box plot
b@2272 35 print("Use: python score_plot.py [rating folder] [plot_type] [-l/-legend]")
b@2272 36 print("Type 'python score_plot.py -h' for help.")
b@2272 37 print("Using default path: " + rating_folder + " with boxplot.")
b@2264 38 else:
b@2264 39 for arg in sys.argv: # go over all arguments
b@2264 40 if arg == '-h':
b@2264 41 # show help
b@2264 42 #TODO: replace with contents of helpfile score_plot.info (or similar)
b@2272 43 print("Use: python score_plot.py [rating_folder] [plot_type] [-l] [confidence]")
b@2272 44 print(" rating_folder:")
b@2272 45 print(" folder where output of 'score_parser' can be found, and")
b@2272 46 print(" where plots will be stored.")
b@2272 47 print(" By default, '../saves/ratings/' is used.")
b@2272 48 print("")
b@2272 49 print("PLOT TYPES")
b@2272 50 print(" Can be used in combination.")
b@2272 51 print(" box | boxplot | -b")
b@2272 52 print(" Enables the boxplot" )
b@2272 53 print(" conf | confidence | -c")
b@2272 54 print(" Enables the confidence interval plot" )
b@2272 55 print(" ind | individual | -i")
b@2272 56 print(" Enables plot of individual ratings" )
b@2272 57 print("")
b@2272 58 print("PLOT OPTIONS")
b@2272 59 print(" leg | legend | -l")
b@2272 60 print(" For individual plot: show legend with individual file names")
b@2272 61 print(" numeric value between 0 and 1, e.g. 0.95")
b@2272 62 print(" For confidence interval plot: confidence value")
b@2264 63 assert False, ""# stop immediately after showing help #TODO cleaner way
b@2264 64
b@2264 65 # PLOT TYPES
b@2264 66 elif arg == 'box' or arg == 'boxplot' or arg == '-b':
b@2264 67 enable_boxplot = True # show box plot
b@2264 68 elif arg == 'conf' or arg == 'confidence' or arg == '-c':
b@2264 69 enable_confidence = True # show confidence interval
b@2264 70 #TODO add confidence value input
b@2264 71 elif arg == 'ind' or arg == 'individual' or arg == '-i':
b@2264 72 enable_individual = True # show all individual ratings
nicholas@3107 73 elif arg == 'comb' or arg == 'combined' or arg == '-m':
nicholas@3107 74 enable_combined = True # show combined plot with error bars
b@2264 75 # PLOT OPTIONS
b@2264 76 elif arg == 'leg' or arg == 'legend' or arg == '-l':
b@2264 77 if not enable_individual:
b@2272 78 print("WARNING: The 'legend' option is only relevant to plots of "+\
b@2272 79 "individual ratings")
b@2264 80 show_legend = True # show all individual ratings
b@2264 81 elif arg.isdigit():
b@2264 82 if not enable_confidence:
b@2272 83 print("WARNING: The numeric confidence value is only relevant when "+\
b@2272 84 "confidence plot is enabled")
b@2264 85 if float(arg)>0 and float(arg)<1:
b@2264 86 confidence = float(arg)
b@2264 87 else:
b@2272 88 print("WARNING: The confidence value needs to be between 0 and 1")
b@2264 89
b@2264 90 # FOLDER NAME
b@2264 91 else:
b@2264 92 # assume it's the folder name
b@2264 93 rating_folder = arg
b@2264 94
b@2264 95 # at least one plot type should be selected: box plot by default
nicholas@3107 96 if not enable_boxplot and not enable_confidence and not enable_individual and not enable_combined:
nicholas@3107 97 print("Default to enable boxplot")
b@2264 98 enable_boxplot = True
b@2264 99
b@2264 100 # check if folder_name exists
b@2264 101 if not os.path.exists(rating_folder):
b@2264 102 #the file is not there
b@2272 103 print("Folder '"+rating_folder+"' does not exist.")
b@2264 104 sys.exit() # terminate script execution
b@2264 105 elif not os.access(os.path.dirname(rating_folder), os.W_OK):
b@2264 106 #the file does exist but write rating_folder are not given
b@2272 107 print("No write privileges in folder '"+rating_folder+"'.")
b@2264 108
b@2264 109
b@2264 110 # CONFIGURATION
b@2264 111
b@2264 112 # Font settings
b@2264 113 font = {'weight' : 'bold',
b@2264 114 'size' : 10}
b@2264 115 plt.rc('font', **font)
b@2264 116
b@2264 117
b@2264 118 # CODE
nicholas@3107 119 combined = {}
b@2264 120
b@2264 121 # get every csv file in folder
b@2264 122 for file in os.listdir(rating_folder):
b@2264 123 if file.endswith(".csv"):
b@2264 124 page_name = file[:-4] # file name (without extension) is page ID
b@2264 125
b@2272 126 # get header (as text)
b@2272 127 with open(rating_folder+file, 'rt') as readfile: # read this csv file
b@2272 128 filereader = csv.reader(readfile, delimiter=',')
b@2272 129 headerrow = next(filereader) # use headerrow as X-axis
b@2272 130 headerrow = headerrow[1:]
b@2272 131
b@2272 132 # read ratings into matrix (as bytes)
b@2264 133 with open(rating_folder+file, 'rb') as readfile: # read this csv file
b@2264 134 filereader = csv.reader(readfile, delimiter=',')
b@2264 135 ratings = np.genfromtxt(readfile,
b@2264 136 delimiter=",",
b@2272 137 skip_header = 1,
b@2264 138 converters = {3: lambda s: float(s or 'Nan')},
b@2272 139 usecols=list(range(1,len(headerrow)+1))
b@2264 140 )
b@2264 141
b@2264 142 # assert at least 2 subjects (move on to next file if violated)
b@2264 143 if ratings.shape[0]<2:
b@2272 144 print("WARNING: Just one subject for " + page_name + ". Moving on to next file.")
b@2264 145 break
b@2264 146
b@2489 147 if len(ratings.shape) <= 1: # if only single subject
b@2489 148 ratings = [[r] for r in ratings] # turn into array of arrays
b@2489 149
b@2264 150 # BOXPLOT
b@2264 151 if enable_boxplot:
b@2264 152 plt.boxplot(ratings)
b@2264 153
b@2264 154 # CONFIDENCE INTERVAL
b@2264 155 if enable_confidence:
b@2264 156 iterator = 0
b@2264 157 for column in ratings.T: # iterate over transposed matrix
b@2264 158 # remove all 'Nan's from column
b@2264 159 column = column[~np.isnan(column)]
b@2264 160
b@2264 161 # get number of non-Nan ratings (= #subjects)
b@2264 162 n = column.size
b@2264 163
b@2264 164 # get mean
b@2264 165 mean_rating = np.mean(column)
b@2264 166
b@2264 167 # get errors
b@2264 168 err = scipy.stats.sem(column)* sp.stats.t._ppf((1+confidence)/2., n-1)
b@2264 169
b@2264 170 # draw plot
b@2264 171 plt.errorbar(iterator+1,
b@2264 172 mean_rating,
b@2264 173 yerr=err,
b@2264 174 marker="x",
b@2264 175 color ="k",
b@2264 176 markersize=12,
b@2264 177 linestyle='None')
b@2264 178
b@2264 179 iterator += 1 # increase counter
b@2264 180
b@2264 181
b@2264 182 # INDIVIDUAL PLOT
b@2264 183 if enable_individual or show_individual:
b@2264 184 # marker list and color map to cycle through
b@2264 185 markerlist = ["x", ".", "o", "*", "+", "v", ">", "<", "8", "s", "p"]
b@2264 186 colormap = ['b', 'r', 'g', 'c', 'm', 'y', 'k']
b@2264 187 increment = 0
b@2264 188 linehandles = []
b@2264 189 legendnames = []
b@2272 190 with open(rating_folder+file, 'r') as readfile: # read this csv file
b@2264 191 filereader = csv.reader(readfile, delimiter=',')
b@2272 192 headerrow = next(filereader) # use headerrow as X-axis
b@2264 193 headerrow = headerrow[1:]
b@2264 194 for row in filereader:
b@2264 195 subject_id = row[0][:-4] # read from beginning of line
b@2264 196 # assume plotting all individuals if no individual(s) specified
b@2264 197 if not show_individual or subject_id in show_individual:
b@2264 198 plothandle, = plt.plot(range(1,len(row)), # x-values
b@2264 199 ratings[increment,:],#row[1:], # y-values: csv values except subject name
b@2264 200 color=colormap[increment%len(colormap)],
b@2264 201 marker=markerlist[increment%len(markerlist)],
b@2264 202 markersize=10,
b@2264 203 linestyle='None',
b@2264 204 label=subject_id
b@2264 205 )
b@2264 206 linehandles.append(plothandle)
b@2264 207 legendnames.append(subject_id)
b@2264 208 if show_legend:
b@2264 209 plt.legend(linehandles, legendnames,
b@2264 210 loc='upper right',
b@2264 211 bbox_to_anchor=(1.1, 1),
b@2264 212 borderaxespad=0.,
b@2264 213 numpoints=1 # remove extra marker
b@2264 214 )
b@2264 215 increment += 1 # increase counter
nicholas@3107 216 if enable_combined:
nicholas@3107 217 print(page_name)
nicholas@3107 218 combined[page_name] = {"labels": headerrow, "r": ratings}
b@2264 219
nicholas@3107 220 if enable_boxplot or enable_confidence or enable_individual:
nicholas@3107 221 # TITLE, AXIS LABELS AND LIMITS
nicholas@3107 222 plt.title(page_name)
nicholas@3107 223 plt.xlabel('Fragment')
nicholas@3107 224 plt.xlim(0, len(headerrow)+1) # only show relevant region, leave space left & right)
nicholas@3107 225 plt.xticks(range(1, len(headerrow)+1), headerrow, rotation=90) # show fragment names
nicholas@3107 226 plt.ylabel('Rating')
nicholas@3107 227 plt.ylim(0,1)
nicholas@3107 228 # SHOW PLOT
nicholas@3107 229 #plt.show()
nicholas@3107 230 #exit()
b@2264 231
nicholas@3107 232 # SAVE PLOT
nicholas@3107 233 # automatically
nicholas@3107 234 plot_type = ("-box" if enable_boxplot else "") + \
b@2264 235 ("-conf" if enable_confidence else "") + \
b@2264 236 ("-ind" if enable_individual else "")
nicholas@3107 237 plt.savefig(rating_folder+page_name+plot_type+".pdf", bbox_inches='tight')
nicholas@3107 238 plt.close()
nicholas@3107 239
nicholas@3107 240 if enable_combined:
nicholas@3107 241 plt.figure()
nicholas@3107 242 pages = combined.keys()
nicholas@3107 243 numcombined = len(pages)
nicholas@3107 244 spacing = 1.0/float(numcombined+2)
nicholas@3107 245 for i in range(0,numcombined):
nicholas@3107 246 page_name = pages[i]
nicholas@3107 247 N = len(combined[page_name]['labels'])
nicholas@3107 248 mean = np.percentile(combined[page_name]['r'], 50, 0)
nicholas@3107 249 p25 = np.percentile(combined[page_name]['r'], 25, 0)
nicholas@3107 250 p75 = np.percentile(combined[page_name]['r'], 75, 0)
nicholas@3107 251 yerr = [mean-p25, p75-mean]
nicholas@3107 252 print(yerr)
nicholas@3107 253 plt.errorbar(np.arange(0,N)+(spacing*(i+1)), combined[page_name]['r'].mean(0), yerr=yerr, fmt='x', elinewidth=0.5)
nicholas@3107 254 ax = plt.gca()
nicholas@3107 255 ax.grid(which='major', axis='x', linewidth=2, color='k')
nicholas@3107 256 plt.show()